Per Nikerabbit, follow-up to r74191: tag for removal in 1.19; I removed the last...
[mediawiki.git] / includes / db / Database.php
blobe249ccb2a0b22c19af17db3111befc2dce5c0aff
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
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
41 * @return bool
42 * @throws DBConnectionError
44 public function open( $server, $user, $password, $dbName );
46 /**
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
52 * @private
54 /*private*/ function doQuery( $sql );
56 /**
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
59 * member variables.
61 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
62 * @return Row object
63 * @throws DBUnexpectedError Thrown if the database returns an error
65 public function fetchObject( $res );
67 /**
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.
72 * @return Row object
73 * @throws DBUnexpectedError Thrown if the database returns an error
75 public function fetchRow( $res );
77 /**
78 * Get the number of rows in a result object
80 * @param $res Mixed: A SQL result
81 * @return int
83 public function numRows( $res );
85 /**
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
90 * @return int
92 public function numFields( $res );
94 /**
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
99 * @param $n Integer
100 * @return string
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()
109 * Example:
110 * $id = $dbw->nextSequenceValue('page_page_id_seq');
111 * $dbw->insert('page',array('page_id' => $id));
112 * $id = $dbw->insertId();
114 * @return int
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
131 * @return int
133 public function lastErrno();
136 * Get a description of the last error
137 * @see http://www.php.net/mysql_error
139 * @return string
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
156 * @return int
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().
182 * @return string: Version information from the database server.
184 public function getServerVersion();
187 * A string describing the current software version, and possibly
188 * other details in a user-friendly way. Will be listed on Special:Version, etc.
189 * Use getServerVersion() to get machine-friendly information.
191 * @return string: Version information from the database server
193 public function getServerInfo();
197 * Database abstraction object
198 * @ingroup Database
200 abstract class DatabaseBase implements DatabaseType {
202 # ------------------------------------------------------------------------------
203 # Variables
204 # ------------------------------------------------------------------------------
206 protected $mLastQuery = '';
207 protected $mDoneWrites = false;
208 protected $mPHPError = false;
210 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
211 protected $mOpened = false;
213 protected $mFailFunction;
214 protected $mTablePrefix;
215 protected $mFlags;
216 protected $mTrxLevel = 0;
217 protected $mErrorCount = 0;
218 protected $mLBInfo = array();
219 protected $mFakeSlaveLag = null, $mFakeMaster = false;
220 protected $mDefaultBigSelects = null;
222 # ------------------------------------------------------------------------------
223 # Accessors
224 # ------------------------------------------------------------------------------
225 # These optionally set a variable and return the previous state
228 * A string describing the current software version, and possibly
229 * other details in a user-friendly way. Will be listed on Special:Version, etc.
230 * Use getServerVersion() to get machine-friendly information.
232 * @return string: Version information from the database server
234 public function getServerInfo() {
235 return $this->getServerVersion();
239 * Fail function, takes a Database as a parameter
240 * Set to false for default, 1 for ignore errors
242 function failFunction( $function = null ) {
243 return wfSetVar( $this->mFailFunction, $function );
247 * Boolean, controls output of large amounts of debug information
249 function debug( $debug = null ) {
250 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
254 * Turns buffering of SQL result sets on (true) or off (false).
255 * Default is "on" and it should not be changed without good reasons.
257 function bufferResults( $buffer = null ) {
258 if ( is_null( $buffer ) ) {
259 return !(bool)( $this->mFlags & DBO_NOBUFFER );
260 } else {
261 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
266 * Turns on (false) or off (true) the automatic generation and sending
267 * of a "we're sorry, but there has been a database error" page on
268 * database errors. Default is on (false). When turned off, the
269 * code should use lastErrno() and lastError() to handle the
270 * situation as appropriate.
272 function ignoreErrors( $ignoreErrors = null ) {
273 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
277 * The current depth of nested transactions
278 * @param $level Integer: , default NULL.
280 function trxLevel( $level = null ) {
281 return wfSetVar( $this->mTrxLevel, $level );
285 * Number of errors logged, only useful when errors are ignored
287 function errorCount( $count = null ) {
288 return wfSetVar( $this->mErrorCount, $count );
291 function tablePrefix( $prefix = null ) {
292 return wfSetVar( $this->mTablePrefix, $prefix );
296 * Properties passed down from the server info array of the load balancer
298 function getLBInfo( $name = null ) {
299 if ( is_null( $name ) ) {
300 return $this->mLBInfo;
301 } else {
302 if ( array_key_exists( $name, $this->mLBInfo ) ) {
303 return $this->mLBInfo[$name];
304 } else {
305 return null;
310 function setLBInfo( $name, $value = null ) {
311 if ( is_null( $value ) ) {
312 $this->mLBInfo = $name;
313 } else {
314 $this->mLBInfo[$name] = $value;
319 * Set lag time in seconds for a fake slave
321 function setFakeSlaveLag( $lag ) {
322 $this->mFakeSlaveLag = $lag;
326 * Make this connection a fake master
328 function setFakeMaster( $enabled = true ) {
329 $this->mFakeMaster = $enabled;
333 * Returns true if this database supports (and uses) cascading deletes
335 function cascadingDeletes() {
336 return false;
340 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
342 function cleanupTriggers() {
343 return false;
347 * Returns true if this database is strict about what can be put into an IP field.
348 * Specifically, it uses a NULL value instead of an empty string.
350 function strictIPs() {
351 return false;
355 * Returns true if this database uses timestamps rather than integers
357 function realTimestamps() {
358 return false;
362 * Returns true if this database does an implicit sort when doing GROUP BY
364 function implicitGroupby() {
365 return true;
369 * Returns true if this database does an implicit order by when the column has an index
370 * For example: SELECT page_title FROM page LIMIT 1
372 function implicitOrderby() {
373 return true;
377 * Returns true if this database requires that SELECT DISTINCT queries require that all
378 ORDER BY expressions occur in the SELECT list per the SQL92 standard
380 function standardSelectDistinct() {
381 return true;
385 * Returns true if this database can do a native search on IP columns
386 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
388 function searchableIPs() {
389 return false;
393 * Returns true if this database can use functional indexes
395 function functionalIndexes() {
396 return false;
400 * Return the last query that went through DatabaseBase::query()
401 * @return String
403 function lastQuery() { return $this->mLastQuery; }
407 * Returns true if the connection may have been used for write queries.
408 * Should return true if unsure.
410 function doneWrites() { return $this->mDoneWrites; }
413 * Is a connection to the database open?
414 * @return Boolean
416 function isOpen() { return $this->mOpened; }
419 * Set a flag for this connection
421 * @param $flag Integer: DBO_* constants from Defines.php:
422 * - DBO_DEBUG: output some debug info (same as debug())
423 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
424 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
425 * - DBO_TRX: automatically start transactions
426 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
427 * and removes it in command line mode
428 * - DBO_PERSISTENT: use persistant database connection
430 function setFlag( $flag ) {
431 $this->mFlags |= $flag;
435 * Clear a flag for this connection
437 * @param $flag: same as setFlag()'s $flag param
439 function clearFlag( $flag ) {
440 $this->mFlags &= ~$flag;
444 * Returns a boolean whether the flag $flag is set for this connection
446 * @param $flag: same as setFlag()'s $flag param
447 * @return Boolean
449 function getFlag( $flag ) {
450 return !!( $this->mFlags & $flag );
454 * General read-only accessor
456 function getProperty( $name ) {
457 return $this->$name;
460 function getWikiID() {
461 if ( $this->mTablePrefix ) {
462 return "{$this->mDBname}-{$this->mTablePrefix}";
463 } else {
464 return $this->mDBname;
469 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
471 public function getSchema() {
472 global $IP;
473 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
474 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
475 } else {
476 return "$IP/maintenance/tables.sql";
480 # ------------------------------------------------------------------------------
481 # Other functions
482 # ------------------------------------------------------------------------------
485 * Constructor.
486 * @param $server String: database server host
487 * @param $user String: database user name
488 * @param $password String: database user password
489 * @param $dbName String: database name
490 * @param $failFunction
491 * @param $flags
492 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
494 function __construct( $server = false, $user = false, $password = false, $dbName = false,
495 $failFunction = false, $flags = 0, $tablePrefix = 'get from global'
497 global $wgOut, $wgDBprefix, $wgCommandLineMode;
499 # Can't get a reference if it hasn't been set yet
500 if ( !isset( $wgOut ) ) {
501 $wgOut = null;
504 $this->mFailFunction = $failFunction;
505 $this->mFlags = $flags;
507 if ( $this->mFlags & DBO_DEFAULT ) {
508 if ( $wgCommandLineMode ) {
509 $this->mFlags &= ~DBO_TRX;
510 } else {
511 $this->mFlags |= DBO_TRX;
516 // Faster read-only access
517 if ( wfReadOnly() ) {
518 $this->mFlags |= DBO_PERSISTENT;
519 $this->mFlags &= ~DBO_TRX;
522 /** Get the default table prefix*/
523 if ( $tablePrefix == 'get from global' ) {
524 $this->mTablePrefix = $wgDBprefix;
525 } else {
526 $this->mTablePrefix = $tablePrefix;
529 if ( $server ) {
530 $this->open( $server, $user, $password, $dbName );
535 * Same as new DatabaseMysql( ... ), kept for backward compatibility
536 * @param $server String: database server host
537 * @param $user String: database user name
538 * @param $password String: database user password
539 * @param $dbName String: database name
540 * @param failFunction
541 * @param $flags
543 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
544 wfDeprecated( __METHOD__ );
545 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
548 protected function installErrorHandler() {
549 $this->mPHPError = false;
550 $this->htmlErrors = ini_set( 'html_errors', '0' );
551 set_error_handler( array( $this, 'connectionErrorHandler' ) );
554 protected function restoreErrorHandler() {
555 restore_error_handler();
556 if ( $this->htmlErrors !== false ) {
557 ini_set( 'html_errors', $this->htmlErrors );
559 if ( $this->mPHPError ) {
560 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
561 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
562 return $error;
563 } else {
564 return false;
568 protected function connectionErrorHandler( $errno, $errstr ) {
569 $this->mPHPError = $errstr;
573 * Closes a database connection.
574 * if it is open : commits any open transactions
576 * @return Bool operation success. true if already closed.
578 function close() {
579 # Stub, should probably be overridden
580 return true;
584 * @param $error String: fallback error message, used if none is given by DB
586 function reportConnectionError( $error = 'Unknown error' ) {
587 $myError = $this->lastError();
588 if ( $myError ) {
589 $error = $myError;
592 if ( $this->mFailFunction ) {
593 # Legacy error handling method
594 if ( !is_int( $this->mFailFunction ) ) {
595 $ff = $this->mFailFunction;
596 $ff( $this, $error );
598 } else {
599 # New method
600 throw new DBConnectionError( $this, $error );
605 * Determine whether a query writes to the DB.
606 * Should return true if unsure.
608 function isWriteQuery( $sql ) {
609 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
613 * Usually aborts on failure. If errors are explicitly ignored, returns success.
615 * @param $sql String: SQL query
616 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
617 * comment (you can use __METHOD__ or add some extra info)
618 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
619 * maybe best to catch the exception instead?
620 * @return true for a successful write query, ResultWrapper object for a successful read query,
621 * or false on failure if $tempIgnore set
622 * @throws DBQueryError Thrown when the database returns an error of any kind
624 public function query( $sql, $fname = '', $tempIgnore = false ) {
625 global $wgProfiler;
627 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
628 if ( isset( $wgProfiler ) ) {
629 # generalizeSQL will probably cut down the query to reasonable
630 # logging size most of the time. The substr is really just a sanity check.
632 # Who's been wasting my precious column space? -- TS
633 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
635 if ( $isMaster ) {
636 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
637 $totalProf = 'DatabaseBase::query-master';
638 } else {
639 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
640 $totalProf = 'DatabaseBase::query';
643 wfProfileIn( $totalProf );
644 wfProfileIn( $queryProf );
647 $this->mLastQuery = $sql;
648 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
649 // Set a flag indicating that writes have been done
650 wfDebug( __METHOD__ . ": Writes done: $sql\n" );
651 $this->mDoneWrites = true;
654 # Add a comment for easy SHOW PROCESSLIST interpretation
655 # if ( $fname ) {
656 global $wgUser;
657 if ( is_object( $wgUser ) && !( $wgUser instanceof StubObject ) ) {
658 $userName = $wgUser->getName();
659 if ( mb_strlen( $userName ) > 15 ) {
660 $userName = mb_substr( $userName, 0, 15 ) . '...';
662 $userName = str_replace( '/', '', $userName );
663 } else {
664 $userName = '';
666 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
667 # } else {
668 # $commentedSql = $sql;
671 # If DBO_TRX is set, start a transaction
672 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
673 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
674 // avoid establishing transactions for SHOW and SET statements too -
675 // that would delay transaction initializations to once connection
676 // is really used by application
677 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
678 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
679 $this->begin();
682 if ( $this->debug() ) {
683 static $cnt = 0;
685 $cnt++;
686 $sqlx = substr( $commentedSql, 0, 500 );
687 $sqlx = strtr( $sqlx, "\t\n", ' ' );
689 if ( $isMaster ) {
690 wfDebug( "Query $cnt (master): $sqlx\n" );
691 } else {
692 wfDebug( "Query $cnt (slave): $sqlx\n" );
696 if ( istainted( $sql ) & TC_MYSQL ) {
697 throw new MWException( 'Tainted query found' );
700 # Do the query and handle errors
701 $ret = $this->doQuery( $commentedSql );
703 # Try reconnecting if the connection was lost
704 if ( false === $ret && $this->wasErrorReissuable() ) {
705 # Transaction is gone, like it or not
706 $this->mTrxLevel = 0;
707 wfDebug( "Connection lost, reconnecting...\n" );
709 if ( $this->ping() ) {
710 wfDebug( "Reconnected\n" );
711 $sqlx = substr( $commentedSql, 0, 500 );
712 $sqlx = strtr( $sqlx, "\t\n", ' ' );
713 global $wgRequestTime;
714 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
715 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
716 $ret = $this->doQuery( $commentedSql );
717 } else {
718 wfDebug( "Failed\n" );
722 if ( false === $ret ) {
723 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
726 if ( isset( $wgProfiler ) ) {
727 wfProfileOut( $queryProf );
728 wfProfileOut( $totalProf );
731 return $this->resultObject( $ret );
735 * @param $error String
736 * @param $errno Integer
737 * @param $sql String
738 * @param $fname String
739 * @param $tempIgnore Boolean
741 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
742 # Ignore errors during error handling to avoid infinite recursion
743 $ignore = $this->ignoreErrors( true );
744 ++$this->mErrorCount;
746 if ( $ignore || $tempIgnore ) {
747 wfDebug( "SQL ERROR (ignored): $error\n" );
748 $this->ignoreErrors( $ignore );
749 } else {
750 $sql1line = str_replace( "\n", "\\n", $sql );
751 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
752 wfDebug( "SQL ERROR: " . $error . "\n" );
753 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
759 * Intended to be compatible with the PEAR::DB wrapper functions.
760 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
762 * ? = scalar value, quoted as necessary
763 * ! = raw SQL bit (a function for instance)
764 * & = filename; reads the file and inserts as a blob
765 * (we don't use this though...)
767 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
768 /* MySQL doesn't support prepared statements (yet), so just
769 pack up the query for reference. We'll manually replace
770 the bits later. */
771 return array( 'query' => $sql, 'func' => $func );
774 function freePrepared( $prepared ) {
775 /* No-op by default */
779 * Execute a prepared query with the various arguments
780 * @param $prepared String: the prepared sql
781 * @param $args Mixed: Either an array here, or put scalars as varargs
783 function execute( $prepared, $args = null ) {
784 if ( !is_array( $args ) ) {
785 # Pull the var args
786 $args = func_get_args();
787 array_shift( $args );
790 $sql = $this->fillPrepared( $prepared['query'], $args );
792 return $this->query( $sql, $prepared['func'] );
796 * Prepare & execute an SQL statement, quoting and inserting arguments
797 * in the appropriate places.
798 * @param $query String
799 * @param $args ...
801 function safeQuery( $query, $args = null ) {
802 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
804 if ( !is_array( $args ) ) {
805 # Pull the var args
806 $args = func_get_args();
807 array_shift( $args );
810 $retval = $this->execute( $prepared, $args );
811 $this->freePrepared( $prepared );
813 return $retval;
817 * For faking prepared SQL statements on DBs that don't support
818 * it directly.
819 * @param $preparedQuery String: a 'preparable' SQL statement
820 * @param $args Array of arguments to fill it with
821 * @return string executable SQL
823 function fillPrepared( $preparedQuery, $args ) {
824 reset( $args );
825 $this->preparedArgs =& $args;
827 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
828 array( &$this, 'fillPreparedArg' ), $preparedQuery );
832 * preg_callback func for fillPrepared()
833 * The arguments should be in $this->preparedArgs and must not be touched
834 * while we're doing this.
836 * @param $matches Array
837 * @return String
838 * @private
840 function fillPreparedArg( $matches ) {
841 switch( $matches[1] ) {
842 case '\\?': return '?';
843 case '\\!': return '!';
844 case '\\&': return '&';
847 list( /* $n */ , $arg ) = each( $this->preparedArgs );
849 switch( $matches[1] ) {
850 case '?': return $this->addQuotes( $arg );
851 case '!': return $arg;
852 case '&':
853 # return $this->addQuotes( file_get_contents( $arg ) );
854 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
855 default:
856 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
861 * Free a result object
862 * @param $res Mixed: A SQL result
864 function freeResult( $res ) {
865 # Stub. Might not really need to be overridden, since results should
866 # be freed by PHP when the variable goes out of scope anyway.
870 * Simple UPDATE wrapper
871 * Usually aborts on failure
872 * If errors are explicitly ignored, returns success
874 * This function exists for historical reasons, DatabaseBase::update() has a more standard
875 * calling convention and feature set
877 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
878 $table = $this->tableName( $table );
879 $sql = "UPDATE $table SET $var = '" .
880 $this->strencode( $value ) . "' WHERE ($cond)";
882 return (bool)$this->query( $sql, $fname );
886 * Simple SELECT wrapper, returns a single field, input must be encoded
887 * Usually aborts on failure
888 * If errors are explicitly ignored, returns FALSE on failure
890 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
891 if ( !is_array( $options ) ) {
892 $options = array( $options );
895 $options['LIMIT'] = 1;
897 $res = $this->select( $table, $var, $cond, $fname, $options );
899 if ( $res === false || !$this->numRows( $res ) ) {
900 return false;
903 $row = $this->fetchRow( $res );
905 if ( $row !== false ) {
906 return reset( $row );
907 } else {
908 return false;
913 * Returns an optional USE INDEX clause to go after the table, and a
914 * string to go at the end of the query
916 * @private
918 * @param $options Array: associative array of options to be turned into
919 * an SQL query, valid keys are listed in the function.
920 * @return Array
922 function makeSelectOptions( $options ) {
923 $preLimitTail = $postLimitTail = '';
924 $startOpts = '';
926 $noKeyOptions = array();
928 foreach ( $options as $key => $option ) {
929 if ( is_numeric( $key ) ) {
930 $noKeyOptions[$option] = true;
934 if ( isset( $options['GROUP BY'] ) ) {
935 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
938 if ( isset( $options['HAVING'] ) ) {
939 $preLimitTail .= " HAVING {$options['HAVING']}";
942 if ( isset( $options['ORDER BY'] ) ) {
943 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
946 // if (isset($options['LIMIT'])) {
947 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
948 // isset($options['OFFSET']) ? $options['OFFSET']
949 // : false);
950 // }
952 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
953 $postLimitTail .= ' FOR UPDATE';
956 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
957 $postLimitTail .= ' LOCK IN SHARE MODE';
960 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
961 $startOpts .= 'DISTINCT';
964 # Various MySQL extensions
965 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
966 $startOpts .= ' /*! STRAIGHT_JOIN */';
969 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
970 $startOpts .= ' HIGH_PRIORITY';
973 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
974 $startOpts .= ' SQL_BIG_RESULT';
977 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
978 $startOpts .= ' SQL_BUFFER_RESULT';
981 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
982 $startOpts .= ' SQL_SMALL_RESULT';
985 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
986 $startOpts .= ' SQL_CALC_FOUND_ROWS';
989 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
990 $startOpts .= ' SQL_CACHE';
993 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
994 $startOpts .= ' SQL_NO_CACHE';
997 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
998 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
999 } else {
1000 $useIndex = '';
1003 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1007 * SELECT wrapper
1009 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1010 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1011 * @param $conds Mixed: Array or string, condition(s) for WHERE
1012 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1013 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1014 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1015 * @param $join_conds Array: Associative array of table join conditions (optional)
1016 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1017 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
1019 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1020 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1022 return $this->query( $sql, $fname );
1026 * SELECT wrapper
1028 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1029 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1030 * @param $conds Mixed: Array or string, condition(s) for WHERE
1031 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1032 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1033 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1034 * @param $join_conds Array: Associative array of table join conditions (optional)
1035 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1036 * @return string, the SQL text
1038 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1039 if ( is_array( $vars ) ) {
1040 $vars = implode( ',', $vars );
1043 if ( !is_array( $options ) ) {
1044 $options = array( $options );
1047 if ( is_array( $table ) ) {
1048 if ( !empty( $join_conds ) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1049 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1050 } else {
1051 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1053 } elseif ( $table != '' ) {
1054 if ( $table { 0 } == ' ' ) {
1055 $from = ' FROM ' . $table;
1056 } else {
1057 $from = ' FROM ' . $this->tableName( $table );
1059 } else {
1060 $from = '';
1063 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1065 if ( !empty( $conds ) ) {
1066 if ( is_array( $conds ) ) {
1067 $conds = $this->makeList( $conds, LIST_AND );
1069 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1070 } else {
1071 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1074 if ( isset( $options['LIMIT'] ) )
1075 $sql = $this->limitResult( $sql, $options['LIMIT'],
1076 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1077 $sql = "$sql $postLimitTail";
1079 if ( isset( $options['EXPLAIN'] ) ) {
1080 $sql = 'EXPLAIN ' . $sql;
1083 return $sql;
1087 * Single row SELECT wrapper
1088 * Aborts or returns FALSE on error
1090 * @param $table String: table name
1091 * @param $vars String: the selected variables
1092 * @param $conds Array: a condition map, terms are ANDed together.
1093 * Items with numeric keys are taken to be literal conditions
1094 * Takes an array of selected variables, and a condition map, which is ANDed
1095 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1096 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1097 * $obj- >page_id is the ID of the Astronomy article
1098 * @param $fname String: Calling function name
1099 * @param $options Array
1100 * @param $join_conds Array
1102 * @todo migrate documentation to phpdocumentor format
1104 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1105 $options['LIMIT'] = 1;
1106 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1108 if ( $res === false ) {
1109 return false;
1112 if ( !$this->numRows( $res ) ) {
1113 return false;
1116 $obj = $this->fetchObject( $res );
1118 return $obj;
1122 * Estimate rows in dataset
1123 * Returns estimated count - not necessarily an accurate estimate across different databases,
1124 * so use sparingly
1125 * Takes same arguments as DatabaseBase::select()
1127 * @param $table String: table name
1128 * @param $vars Array: unused
1129 * @param $conds Array: filters on the table
1130 * @param $fname String: function name for profiling
1131 * @param $options Array: options for select
1132 * @return Integer: row count
1134 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1135 $rows = 0;
1136 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1138 if ( $res ) {
1139 $row = $this->fetchRow( $res );
1140 $rows = ( isset( $row['rowcount'] ) ) ? $row['rowcount'] : 0;
1143 return $rows;
1147 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1148 * It's only slightly flawed. Don't use for anything important.
1150 * @param $sql String: A SQL Query
1152 static function generalizeSQL( $sql ) {
1153 # This does the same as the regexp below would do, but in such a way
1154 # as to avoid crashing php on some large strings.
1155 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1157 $sql = str_replace ( "\\\\", '', $sql );
1158 $sql = str_replace ( "\\'", '', $sql );
1159 $sql = str_replace ( "\\\"", '', $sql );
1160 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1161 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1163 # All newlines, tabs, etc replaced by single space
1164 $sql = preg_replace ( '/\s+/', ' ', $sql );
1166 # All numbers => N
1167 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1169 return $sql;
1173 * Determines whether a field exists in a table
1175 * @param $table String: table name
1176 * @param $field String: filed to check on that table
1177 * @param $fname String: calling function name (optional)
1178 * @return Boolean: whether $table has filed $field
1180 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1181 $info = $this->fieldInfo( $table, $field );
1183 return (bool)$info;
1187 * Determines whether an index exists
1188 * Usually aborts on failure
1189 * If errors are explicitly ignored, returns NULL on failure
1191 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1192 $info = $this->indexInfo( $table, $index, $fname );
1193 if ( is_null( $info ) ) {
1194 return null;
1195 } else {
1196 return $info !== false;
1202 * Get information about an index into an object
1203 * Returns false if the index does not exist
1205 function indexInfo( $table, $index, $fname = 'DatabaseBase::indexInfo' ) {
1206 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1207 # SHOW INDEX should work for 3.x and up:
1208 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1209 $table = $this->tableName( $table );
1210 $index = $this->indexName( $index );
1211 $sql = 'SHOW INDEX FROM ' . $table;
1212 $res = $this->query( $sql, $fname );
1214 if ( !$res ) {
1215 return null;
1218 $result = array();
1220 while ( $row = $this->fetchObject( $res ) ) {
1221 if ( $row->Key_name == $index ) {
1222 $result[] = $row;
1226 return empty( $result ) ? false : $result;
1230 * Query whether a given table exists
1232 function tableExists( $table ) {
1233 $table = $this->tableName( $table );
1234 $old = $this->ignoreErrors( true );
1235 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__ );
1236 $this->ignoreErrors( $old );
1238 return (bool)$res;
1242 * mysql_field_type() wrapper
1244 function fieldType( $res, $index ) {
1245 if ( $res instanceof ResultWrapper ) {
1246 $res = $res->result;
1249 return mysql_field_type( $res, $index );
1253 * Determines if a given index is unique
1255 function indexUnique( $table, $index ) {
1256 $indexInfo = $this->indexInfo( $table, $index );
1258 if ( !$indexInfo ) {
1259 return null;
1262 return !$indexInfo[0]->Non_unique;
1266 * INSERT wrapper, inserts an array into a table
1268 * $a may be a single associative array, or an array of these with numeric keys, for
1269 * multi-row insert.
1271 * Usually aborts on failure
1272 * If errors are explicitly ignored, returns success
1274 * @param $table String: table name (prefix auto-added)
1275 * @param $a Array: Array of rows to insert
1276 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1277 * @param $options Mixed: Associative array of options
1279 * @return bool
1281 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1282 # No rows to insert, easy just return now
1283 if ( !count( $a ) ) {
1284 return true;
1287 $table = $this->tableName( $table );
1289 if ( !is_array( $options ) ) {
1290 $options = array( $options );
1293 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1294 $multi = true;
1295 $keys = array_keys( $a[0] );
1296 } else {
1297 $multi = false;
1298 $keys = array_keys( $a );
1301 $sql = 'INSERT ' . implode( ' ', $options ) .
1302 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1304 if ( $multi ) {
1305 $first = true;
1306 foreach ( $a as $row ) {
1307 if ( $first ) {
1308 $first = false;
1309 } else {
1310 $sql .= ',';
1312 $sql .= '(' . $this->makeList( $row ) . ')';
1314 } else {
1315 $sql .= '(' . $this->makeList( $a ) . ')';
1318 return (bool)$this->query( $sql, $fname );
1322 * Make UPDATE options for the DatabaseBase::update function
1324 * @private
1325 * @param $options Array: The options passed to DatabaseBase::update
1326 * @return string
1328 function makeUpdateOptions( $options ) {
1329 if ( !is_array( $options ) ) {
1330 $options = array( $options );
1333 $opts = array();
1335 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1336 $opts[] = $this->lowPriorityOption();
1339 if ( in_array( 'IGNORE', $options ) ) {
1340 $opts[] = 'IGNORE';
1343 return implode( ' ', $opts );
1347 * UPDATE wrapper, takes a condition array and a SET array
1349 * @param $table String: The table to UPDATE
1350 * @param $values Array: An array of values to SET
1351 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1352 * @param $fname String: The Class::Function calling this function
1353 * (for the log)
1354 * @param $options Array: An array of UPDATE options, can be one or
1355 * more of IGNORE, LOW_PRIORITY
1356 * @return Boolean
1358 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1359 $table = $this->tableName( $table );
1360 $opts = $this->makeUpdateOptions( $options );
1361 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1363 if ( $conds != '*' ) {
1364 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1367 return $this->query( $sql, $fname );
1371 * Makes an encoded list of strings from an array
1372 * $mode:
1373 * LIST_COMMA - comma separated, no field names
1374 * LIST_AND - ANDed WHERE clause (without the WHERE)
1375 * LIST_OR - ORed WHERE clause (without the WHERE)
1376 * LIST_SET - comma separated with field names, like a SET clause
1377 * LIST_NAMES - comma separated field names
1379 function makeList( $a, $mode = LIST_COMMA ) {
1380 if ( !is_array( $a ) ) {
1381 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1384 $first = true;
1385 $list = '';
1387 foreach ( $a as $field => $value ) {
1388 if ( !$first ) {
1389 if ( $mode == LIST_AND ) {
1390 $list .= ' AND ';
1391 } elseif ( $mode == LIST_OR ) {
1392 $list .= ' OR ';
1393 } else {
1394 $list .= ',';
1396 } else {
1397 $first = false;
1400 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1401 $list .= "($value)";
1402 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1403 $list .= "$value";
1404 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1405 if ( count( $value ) == 0 ) {
1406 throw new MWException( __METHOD__ . ': empty input' );
1407 } elseif ( count( $value ) == 1 ) {
1408 // Special-case single values, as IN isn't terribly efficient
1409 // Don't necessarily assume the single key is 0; we don't
1410 // enforce linear numeric ordering on other arrays here.
1411 $value = array_values( $value );
1412 $list .= $field . " = " . $this->addQuotes( $value[0] );
1413 } else {
1414 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1416 } elseif ( $value === null ) {
1417 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1418 $list .= "$field IS ";
1419 } elseif ( $mode == LIST_SET ) {
1420 $list .= "$field = ";
1422 $list .= 'NULL';
1423 } else {
1424 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1425 $list .= "$field = ";
1427 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1431 return $list;
1435 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1436 * The keys on each level may be either integers or strings.
1438 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1439 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1440 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1441 * @return Mixed: string SQL fragment, or false if no items in array.
1443 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1444 $conds = array();
1446 foreach ( $data as $base => $sub ) {
1447 if ( count( $sub ) ) {
1448 $conds[] = $this->makeList(
1449 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1450 LIST_AND );
1454 if ( $conds ) {
1455 return $this->makeList( $conds, LIST_OR );
1456 } else {
1457 // Nothing to search for...
1458 return false;
1463 * Bitwise operations
1466 function bitNot( $field ) {
1467 return "(~$field)";
1470 function bitAnd( $fieldLeft, $fieldRight ) {
1471 return "($fieldLeft & $fieldRight)";
1474 function bitOr( $fieldLeft, $fieldRight ) {
1475 return "($fieldLeft | $fieldRight)";
1479 * Change the current database
1481 * @todo Explain what exactly will fail if this is not overridden.
1482 * @return bool Success or failure
1484 function selectDB( $db ) {
1485 # Stub. Shouldn't cause serious problems if it's not overridden, but
1486 # if your database engine supports a concept similar to MySQL's
1487 # databases you may as well.
1488 return true;
1492 * Get the current DB name
1494 function getDBname() {
1495 return $this->mDBname;
1499 * Get the server hostname or IP address
1501 function getServer() {
1502 return $this->mServer;
1506 * Format a table name ready for use in constructing an SQL query
1508 * This does two important things: it quotes the table names to clean them up,
1509 * and it adds a table prefix if only given a table name with no quotes.
1511 * All functions of this object which require a table name call this function
1512 * themselves. Pass the canonical name to such functions. This is only needed
1513 * when calling query() directly.
1515 * @param $name String: database table name
1516 * @return String: full database name
1518 function tableName( $name ) {
1519 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1520 # Skip the entire process when we have a string quoted on both ends.
1521 # Note that we check the end so that we will still quote any use of
1522 # use of `database`.table. But won't break things if someone wants
1523 # to query a database table with a dot in the name.
1524 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1525 return $name;
1528 # Lets test for any bits of text that should never show up in a table
1529 # name. Basically anything like JOIN or ON which are actually part of
1530 # SQL queries, but may end up inside of the table value to combine
1531 # sql. Such as how the API is doing.
1532 # Note that we use a whitespace test rather than a \b test to avoid
1533 # any remote case where a word like on may be inside of a table name
1534 # surrounded by symbols which may be considered word breaks.
1535 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1536 return $name;
1539 # Split database and table into proper variables.
1540 # We reverse the explode so that database.table and table both output
1541 # the correct table.
1542 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1543 if ( isset( $dbDetails[1] ) ) {
1544 @list( $table, $database ) = $dbDetails;
1545 } else {
1546 @list( $table ) = $dbDetails;
1548 $prefix = $this->mTablePrefix; # Default prefix
1550 # A database name has been specified in input. Quote the table name
1551 # because we don't want any prefixes added.
1552 if ( isset( $database ) ) {
1553 $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1556 # Note that we use the long format because php will complain in in_array if
1557 # the input is not an array, and will complain in is_array if it is not set.
1558 if ( !isset( $database ) # Don't use shared database if pre selected.
1559 && isset( $wgSharedDB ) # We have a shared database
1560 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1561 && isset( $wgSharedTables )
1562 && is_array( $wgSharedTables )
1563 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1564 $database = $wgSharedDB;
1565 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1568 # Quote the $database and $table and apply the prefix if not quoted.
1569 if ( isset( $database ) ) {
1570 $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1572 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1574 # Merge our database and table into our final table name.
1575 $tableName = ( isset( $database ) ? "{$database}.{$table}" : "{$table}" );
1577 return $tableName;
1581 * Fetch a number of table names into an array
1582 * This is handy when you need to construct SQL for joins
1584 * Example:
1585 * extract($dbr->tableNames('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 tableNames() {
1590 $inArray = func_get_args();
1591 $retVal = array();
1593 foreach ( $inArray as $name ) {
1594 $retVal[$name] = $this->tableName( $name );
1597 return $retVal;
1601 * Fetch a number of table names into an zero-indexed numerical array
1602 * This is handy when you need to construct SQL for joins
1604 * Example:
1605 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1606 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1607 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1609 public function tableNamesN() {
1610 $inArray = func_get_args();
1611 $retVal = array();
1613 foreach ( $inArray as $name ) {
1614 $retVal[] = $this->tableName( $name );
1617 return $retVal;
1621 * @private
1623 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1624 $ret = array();
1625 $retJOIN = array();
1626 $use_index_safe = is_array( $use_index ) ? $use_index : array();
1627 $join_conds_safe = is_array( $join_conds ) ? $join_conds : array();
1629 foreach ( $tables as $table ) {
1630 // Is there a JOIN and INDEX clause for this table?
1631 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
1632 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1633 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1634 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND );
1636 if ( $on != '' ) {
1637 $tableClause .= ' ON (' . $on . ')';
1640 $retJOIN[] = $tableClause;
1641 // Is there an INDEX clause?
1642 } else if ( isset( $use_index_safe[$table] ) ) {
1643 $tableClause = $this->tableName( $table );
1644 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1645 $ret[] = $tableClause;
1646 // Is there a JOIN clause?
1647 } else if ( isset( $join_conds_safe[$table] ) ) {
1648 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1649 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND );
1651 if ( $on != '' ) {
1652 $tableClause .= ' ON (' . $on . ')';
1655 $retJOIN[] = $tableClause;
1656 } else {
1657 $tableClause = $this->tableName( $table );
1658 $ret[] = $tableClause;
1662 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1663 $straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1664 $otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1666 // Compile our final table clause
1667 return implode( ' ', array( $straightJoins, $otherJoins ) );
1671 * Get the name of an index in a given table
1673 function indexName( $index ) {
1674 // Backwards-compatibility hack
1675 $renamed = array(
1676 'ar_usertext_timestamp' => 'usertext_timestamp',
1677 'un_user_id' => 'user_id',
1678 'un_user_ip' => 'user_ip',
1681 if ( isset( $renamed[$index] ) ) {
1682 return $renamed[$index];
1683 } else {
1684 return $index;
1689 * If it's a string, adds quotes and backslashes
1690 * Otherwise returns as-is
1692 function addQuotes( $s ) {
1693 if ( $s === null ) {
1694 return 'NULL';
1695 } else {
1696 # This will also quote numeric values. This should be harmless,
1697 # and protects against weird problems that occur when they really
1698 # _are_ strings such as article titles and string->number->string
1699 # conversion is not 1:1.
1700 return "'" . $this->strencode( $s ) . "'";
1705 * Escape string for safe LIKE usage.
1706 * WARNING: you should almost never use this function directly,
1707 * instead use buildLike() that escapes everything automatically
1708 * Deprecated in 1.17, warnings in 1.17, removed in ???
1710 public function escapeLike( $s ) {
1711 wfDeprecated( __METHOD__ );
1712 return $this->escapeLikeInternal( $s );
1715 protected function escapeLikeInternal( $s ) {
1716 $s = str_replace( '\\', '\\\\', $s );
1717 $s = $this->strencode( $s );
1718 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1720 return $s;
1724 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1725 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1726 * Alternatively, the function could be provided with an array of aforementioned parameters.
1728 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1729 * for subpages of 'My page title'.
1730 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1732 * @since 1.16
1733 * @return String: fully built LIKE statement
1735 function buildLike() {
1736 $params = func_get_args();
1738 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1739 $params = $params[0];
1742 $s = '';
1744 foreach ( $params as $value ) {
1745 if ( $value instanceof LikeMatch ) {
1746 $s .= $value->toString();
1747 } else {
1748 $s .= $this->escapeLikeInternal( $value );
1752 return " LIKE '" . $s . "' ";
1756 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1758 function anyChar() {
1759 return new LikeMatch( '_' );
1763 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1765 function anyString() {
1766 return new LikeMatch( '%' );
1770 * Returns an appropriately quoted sequence value for inserting a new row.
1771 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1772 * subclass will return an integer, and save the value for insertId()
1774 function nextSequenceValue( $seqName ) {
1775 return null;
1779 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1780 * is only needed because a) MySQL must be as efficient as possible due to
1781 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1782 * which index to pick. Anyway, other databases might have different
1783 * indexes on a given table. So don't bother overriding this unless you're
1784 * MySQL.
1786 function useIndexClause( $index ) {
1787 return '';
1791 * REPLACE query wrapper
1792 * PostgreSQL simulates this with a DELETE followed by INSERT
1793 * $row is the row to insert, an associative array
1794 * $uniqueIndexes is an array of indexes. Each element may be either a
1795 * field name or an array of field names
1797 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1798 * However if you do this, you run the risk of encountering errors which wouldn't have
1799 * occurred in MySQL
1801 * @param $table String: The table to replace the row(s) in.
1802 * @param $uniqueIndexes Array: An associative array of indexes
1803 * @param $rows Array: Array of rows to replace
1804 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1806 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1807 $table = $this->tableName( $table );
1809 # Single row case
1810 if ( !is_array( reset( $rows ) ) ) {
1811 $rows = array( $rows );
1814 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1815 $first = true;
1817 foreach ( $rows as $row ) {
1818 if ( $first ) {
1819 $first = false;
1820 } else {
1821 $sql .= ',';
1824 $sql .= '(' . $this->makeList( $row ) . ')';
1827 return $this->query( $sql, $fname );
1831 * DELETE where the condition is a join
1832 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1834 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1835 * join condition matches, set $conds='*'
1837 * DO NOT put the join condition in $conds
1839 * @param $delTable String: The table to delete from.
1840 * @param $joinTable String: The other table.
1841 * @param $delVar String: The variable to join on, in the first table.
1842 * @param $joinVar String: The variable to join on, in the second table.
1843 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1844 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1846 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1847 if ( !$conds ) {
1848 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1851 $delTable = $this->tableName( $delTable );
1852 $joinTable = $this->tableName( $joinTable );
1853 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1855 if ( $conds != '*' ) {
1856 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1859 return $this->query( $sql, $fname );
1863 * Returns the size of a text field, or -1 for "unlimited"
1865 function textFieldSize( $table, $field ) {
1866 $table = $this->tableName( $table );
1867 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1868 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1869 $row = $this->fetchObject( $res );
1871 $m = array();
1873 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1874 $size = $m[1];
1875 } else {
1876 $size = -1;
1879 return $size;
1883 * A string to insert into queries to show that they're low-priority, like
1884 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1885 * string and nothing bad should happen.
1887 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1889 function lowPriorityOption() {
1890 return '';
1894 * DELETE query wrapper
1896 * Use $conds == "*" to delete all rows
1898 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1899 if ( !$conds ) {
1900 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1903 $table = $this->tableName( $table );
1904 $sql = "DELETE FROM $table";
1906 if ( $conds != '*' ) {
1907 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1910 return $this->query( $sql, $fname );
1914 * INSERT SELECT wrapper
1915 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1916 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1917 * $conds may be "*" to copy the whole table
1918 * srcTable may be an array of tables.
1920 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1921 $insertOptions = array(), $selectOptions = array() )
1923 $destTable = $this->tableName( $destTable );
1925 if ( is_array( $insertOptions ) ) {
1926 $insertOptions = implode( ' ', $insertOptions );
1929 if ( !is_array( $selectOptions ) ) {
1930 $selectOptions = array( $selectOptions );
1933 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1935 if ( is_array( $srcTable ) ) {
1936 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1937 } else {
1938 $srcTable = $this->tableName( $srcTable );
1941 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1942 " SELECT $startOpts " . implode( ',', $varMap ) .
1943 " FROM $srcTable $useIndex ";
1945 if ( $conds != '*' ) {
1946 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1949 $sql .= " $tailOpts";
1951 return $this->query( $sql, $fname );
1955 * Construct a LIMIT query with optional offset. This is used for query
1956 * pages. The SQL should be adjusted so that only the first $limit rows
1957 * are returned. If $offset is provided as well, then the first $offset
1958 * rows should be discarded, and the next $limit rows should be returned.
1959 * If the result of the query is not ordered, then the rows to be returned
1960 * are theoretically arbitrary.
1962 * $sql is expected to be a SELECT, if that makes a difference. For
1963 * UPDATE, limitResultForUpdate should be used.
1965 * The version provided by default works in MySQL and SQLite. It will very
1966 * likely need to be overridden for most other DBMSes.
1968 * @param $sql String: SQL query we will append the limit too
1969 * @param $limit Integer: the SQL limit
1970 * @param $offset Integer the SQL offset (default false)
1972 function limitResult( $sql, $limit, $offset = false ) {
1973 if ( !is_numeric( $limit ) ) {
1974 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1977 return "$sql LIMIT "
1978 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
1979 . "{$limit} ";
1982 function limitResultForUpdate( $sql, $num ) {
1983 return $this->limitResult( $sql, $num, 0 );
1987 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1988 * within the UNION construct.
1989 * @return Boolean
1991 function unionSupportsOrderAndLimit() {
1992 return true; // True for almost every DB supported
1996 * Construct a UNION query
1997 * This is used for providing overload point for other DB abstractions
1998 * not compatible with the MySQL syntax.
1999 * @param $sqls Array: SQL statements to combine
2000 * @param $all Boolean: use UNION ALL
2001 * @return String: SQL fragment
2003 function unionQueries( $sqls, $all ) {
2004 $glue = $all ? ') UNION ALL (' : ') UNION (';
2005 return '(' . implode( $glue, $sqls ) . ')';
2009 * Returns an SQL expression for a simple conditional. This doesn't need
2010 * to be overridden unless CASE isn't supported in your DBMS.
2012 * @param $cond String: SQL expression which will result in a boolean value
2013 * @param $trueVal String: SQL expression to return if true
2014 * @param $falseVal String: SQL expression to return if false
2015 * @return String: SQL fragment
2017 function conditional( $cond, $trueVal, $falseVal ) {
2018 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2022 * Returns a comand for str_replace function in SQL query.
2023 * Uses REPLACE() in MySQL
2025 * @param $orig String: column to modify
2026 * @param $old String: column to seek
2027 * @param $new String: column to replace with
2029 function strreplace( $orig, $old, $new ) {
2030 return "REPLACE({$orig}, {$old}, {$new})";
2034 * Determines if the last failure was due to a deadlock
2035 * STUB
2037 function wasDeadlock() {
2038 return false;
2042 * Determines if the last query error was something that should be dealt
2043 * with by pinging the connection and reissuing the query.
2044 * STUB
2046 function wasErrorReissuable() {
2047 return false;
2051 * Determines if the last failure was due to the database being read-only.
2052 * STUB
2054 function wasReadOnlyError() {
2055 return false;
2059 * Perform a deadlock-prone transaction.
2061 * This function invokes a callback function to perform a set of write
2062 * queries. If a deadlock occurs during the processing, the transaction
2063 * will be rolled back and the callback function will be called again.
2065 * Usage:
2066 * $dbw->deadlockLoop( callback, ... );
2068 * Extra arguments are passed through to the specified callback function.
2070 * Returns whatever the callback function returned on its successful,
2071 * iteration, or false on error, for example if the retry limit was
2072 * reached.
2074 function deadlockLoop() {
2075 $myFname = 'DatabaseBase::deadlockLoop';
2077 $this->begin();
2078 $args = func_get_args();
2079 $function = array_shift( $args );
2080 $oldIgnore = $this->ignoreErrors( true );
2081 $tries = DEADLOCK_TRIES;
2083 if ( is_array( $function ) ) {
2084 $fname = $function[0];
2085 } else {
2086 $fname = $function;
2089 do {
2090 $retVal = call_user_func_array( $function, $args );
2091 $error = $this->lastError();
2092 $errno = $this->lastErrno();
2093 $sql = $this->lastQuery();
2095 if ( $errno ) {
2096 if ( $this->wasDeadlock() ) {
2097 # Retry
2098 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
2099 } else {
2100 $this->reportQueryError( $error, $errno, $sql, $fname );
2103 } while ( $this->wasDeadlock() && --$tries > 0 );
2105 $this->ignoreErrors( $oldIgnore );
2107 if ( $tries <= 0 ) {
2108 $this->rollback( $myFname );
2109 $this->reportQueryError( $error, $errno, $sql, $fname );
2110 return false;
2111 } else {
2112 $this->commit( $myFname );
2113 return $retVal;
2118 * Do a SELECT MASTER_POS_WAIT()
2120 * @param $pos MySQLMasterPos object
2121 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2123 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
2124 $fname = 'DatabaseBase::masterPosWait';
2125 wfProfileIn( $fname );
2127 # Commit any open transactions
2128 if ( $this->mTrxLevel ) {
2129 $this->commit();
2132 if ( !is_null( $this->mFakeSlaveLag ) ) {
2133 $wait = intval( ( $pos->pos - microtime( true ) + $this->mFakeSlaveLag ) * 1e6 );
2135 if ( $wait > $timeout * 1e6 ) {
2136 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2137 wfProfileOut( $fname );
2138 return -1;
2139 } elseif ( $wait > 0 ) {
2140 wfDebug( "Fake slave waiting $wait us\n" );
2141 usleep( $wait );
2142 wfProfileOut( $fname );
2143 return 1;
2144 } else {
2145 wfDebug( "Fake slave up to date ($wait us)\n" );
2146 wfProfileOut( $fname );
2147 return 0;
2151 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2152 $encFile = $this->addQuotes( $pos->file );
2153 $encPos = intval( $pos->pos );
2154 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2155 $res = $this->doQuery( $sql );
2157 if ( $res && $row = $this->fetchRow( $res ) ) {
2158 wfProfileOut( $fname );
2159 return $row[0];
2160 } else {
2161 wfProfileOut( $fname );
2162 return false;
2167 * Get the position of the master from SHOW SLAVE STATUS
2169 function getSlavePos() {
2170 if ( !is_null( $this->mFakeSlaveLag ) ) {
2171 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
2172 wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
2173 return $pos;
2176 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2177 $row = $this->fetchObject( $res );
2179 if ( $row ) {
2180 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
2181 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
2182 } else {
2183 return false;
2188 * Get the position of the master from SHOW MASTER STATUS
2190 function getMasterPos() {
2191 if ( $this->mFakeMaster ) {
2192 return new MySQLMasterPos( 'fake', microtime( true ) );
2195 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2196 $row = $this->fetchObject( $res );
2198 if ( $row ) {
2199 return new MySQLMasterPos( $row->File, $row->Position );
2200 } else {
2201 return false;
2206 * Begin a transaction, committing any previously open transaction
2208 function begin( $fname = 'DatabaseBase::begin' ) {
2209 $this->query( 'BEGIN', $fname );
2210 $this->mTrxLevel = 1;
2214 * End a transaction
2216 function commit( $fname = 'DatabaseBase::commit' ) {
2217 if ( $this->mTrxLevel ) {
2218 $this->query( 'COMMIT', $fname );
2219 $this->mTrxLevel = 0;
2224 * Rollback a transaction.
2225 * No-op on non-transactional databases.
2227 function rollback( $fname = 'DatabaseBase::rollback' ) {
2228 if ( $this->mTrxLevel ) {
2229 $this->query( 'ROLLBACK', $fname, true );
2230 $this->mTrxLevel = 0;
2235 * Begin a transaction, committing any previously open transaction
2236 * @deprecated use begin()
2238 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2239 wfDeprecated( __METHOD__ );
2240 $this->begin();
2244 * Commit transaction, if one is open
2245 * @deprecated use commit()
2247 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2248 wfDeprecated( __METHOD__ );
2249 $this->commit();
2253 * Creates a new table with structure copied from existing table
2254 * Note that unlike most database abstraction functions, this function does not
2255 * automatically append database prefix, because it works at a lower
2256 * abstraction level.
2258 * @param $oldName String: name of table whose structure should be copied
2259 * @param $newName String: name of table to be created
2260 * @param $temporary Boolean: whether the new table should be temporary
2261 * @param $fname String: calling function name
2262 * @return Boolean: true if operation was successful
2264 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2265 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2269 * Return MW-style timestamp used for MySQL schema
2271 function timestamp( $ts = 0 ) {
2272 return wfTimestamp( TS_MW, $ts );
2276 * Local database timestamp format or null
2278 function timestampOrNull( $ts = null ) {
2279 if ( is_null( $ts ) ) {
2280 return null;
2281 } else {
2282 return $this->timestamp( $ts );
2287 * @todo document
2289 function resultObject( $result ) {
2290 if ( empty( $result ) ) {
2291 return false;
2292 } elseif ( $result instanceof ResultWrapper ) {
2293 return $result;
2294 } elseif ( $result === true ) {
2295 // Successful write query
2296 return $result;
2297 } else {
2298 return new ResultWrapper( $this, $result );
2303 * Return aggregated value alias
2305 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2306 return $valuename;
2310 * Ping the server and try to reconnect if it there is no connection
2312 * @return bool Success or failure
2314 function ping() {
2315 # Stub. Not essential to override.
2316 return true;
2320 * Get slave lag.
2321 * Currently supported only by MySQL
2322 * @return Database replication lag in seconds
2324 function getLag() {
2325 return intval( $this->mFakeSlaveLag );
2329 * Get status information from SHOW STATUS in an associative array
2331 function getStatus( $which = "%" ) {
2332 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2333 $status = array();
2335 while ( $row = $this->fetchObject( $res ) ) {
2336 $status[$row->Variable_name] = $row->Value;
2339 return $status;
2343 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2345 function maxListLen() {
2346 return 0;
2349 function encodeBlob( $b ) {
2350 return $b;
2353 function decodeBlob( $b ) {
2354 return $b;
2358 * Override database's default connection timeout. May be useful for very
2359 * long batch queries such as full-wiki dumps, where a single query reads
2360 * out over hours or days. May or may not be necessary for non-MySQL
2361 * databases. For most purposes, leaving it as a no-op should be fine.
2363 * @param $timeout Integer in seconds
2365 public function setTimeout( $timeout ) {}
2368 * Read and execute SQL commands from a file.
2369 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2370 * @param $filename String: File name to open
2371 * @param $lineCallback Callback: Optional function called before reading each line
2372 * @param $resultCallback Callback: Optional function called for each MySQL result
2373 * @param $fname String: Calling function name or false if name should be generated dynamically
2374 * using $filename
2376 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2377 $fp = fopen( $filename, 'r' );
2379 if ( false === $fp ) {
2380 if ( !defined( "MEDIAWIKI_INSTALL" ) )
2381 throw new MWException( "Could not open \"{$filename}\".\n" );
2382 else
2383 return "Could not open \"{$filename}\".\n";
2386 if ( !$fname ) {
2387 $fname = __METHOD__ . "( $filename )";
2390 try {
2391 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2393 catch ( MWException $e ) {
2394 if ( defined( "MEDIAWIKI_INSTALL" ) ) {
2395 $error = $e->getMessage();
2396 } else {
2397 fclose( $fp );
2398 throw $e;
2402 fclose( $fp );
2404 return $error;
2408 * Get the full path of a patch file. Originally based on archive()
2409 * from updaters.inc. Keep in mind this always returns a patch, as
2410 * it fails back to MySQL if no DB-specific patch can be found
2412 * @param $patch String The name of the patch, like patch-something.sql
2413 * @return String Full path to patch file
2415 public static function patchPath( $patch ) {
2416 global $wgDBtype, $IP;
2418 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2419 return "$IP/maintenance/$wgDBtype/archives/$patch";
2420 } else {
2421 return "$IP/maintenance/archives/$patch";
2426 * Read and execute commands from an open file handle
2427 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2428 * @param $fp String: File handle
2429 * @param $lineCallback Callback: Optional function called before reading each line
2430 * @param $resultCallback Callback: Optional function called for each MySQL result
2431 * @param $fname String: Calling function name
2433 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2434 $cmd = "";
2435 $done = false;
2436 $dollarquote = false;
2438 while ( ! feof( $fp ) ) {
2439 if ( $lineCallback ) {
2440 call_user_func( $lineCallback );
2443 $line = trim( fgets( $fp, 1024 ) );
2444 $sl = strlen( $line ) - 1;
2446 if ( $sl < 0 ) {
2447 continue;
2450 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2451 continue;
2454 # # Allow dollar quoting for function declarations
2455 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2456 if ( $dollarquote ) {
2457 $dollarquote = false;
2458 $done = true;
2460 else {
2461 $dollarquote = true;
2464 else if ( !$dollarquote ) {
2465 if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
2466 $done = true;
2467 $line = substr( $line, 0, $sl );
2471 if ( $cmd != '' ) {
2472 $cmd .= ' ';
2475 $cmd .= "$line\n";
2477 if ( $done ) {
2478 $cmd = str_replace( ';;', ";", $cmd );
2479 $cmd = $this->replaceVars( $cmd );
2480 $res = $this->query( $cmd, $fname );
2482 if ( $resultCallback ) {
2483 call_user_func( $resultCallback, $res, $this );
2486 if ( false === $res ) {
2487 $err = $this->lastError();
2488 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2491 $cmd = '';
2492 $done = false;
2496 return true;
2500 * Replace variables in sourced SQL
2502 protected function replaceVars( $ins ) {
2503 $varnames = array(
2504 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2505 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2506 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2509 // Ordinary variables
2510 foreach ( $varnames as $var ) {
2511 if ( isset( $GLOBALS[$var] ) ) {
2512 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2513 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2514 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2515 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2519 // Table prefixes
2520 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2521 array( $this, 'tableNameCallback' ), $ins );
2523 // Index names
2524 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2525 array( $this, 'indexNameCallback' ), $ins );
2527 return $ins;
2531 * Table name callback
2532 * @private
2534 protected function tableNameCallback( $matches ) {
2535 return $this->tableName( $matches[1] );
2539 * Index name callback
2541 protected function indexNameCallback( $matches ) {
2542 return $this->indexName( $matches[1] );
2546 * Build a concatenation list to feed into a SQL query
2547 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2548 * @return String
2550 function buildConcat( $stringList ) {
2551 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2555 * Acquire a named lock
2557 * Abstracted from Filestore::lock() so child classes can implement for
2558 * their own needs.
2560 * @param $lockName String: name of lock to aquire
2561 * @param $method String: name of method calling us
2562 * @param $timeout Integer: timeout
2563 * @return Boolean
2565 public function lock( $lockName, $method, $timeout = 5 ) {
2566 return true;
2570 * Release a lock.
2572 * @param $lockName String: Name of lock to release
2573 * @param $method String: Name of method calling us
2575 * @return Returns 1 if the lock was released, 0 if the lock was not established
2576 * by this thread (in which case the lock is not released), and NULL if the named
2577 * lock did not exist
2579 public function unlock( $lockName, $method ) {
2580 return true;
2584 * Lock specific tables
2586 * @param $read Array of tables to lock for read access
2587 * @param $write Array of tables to lock for write access
2588 * @param $method String name of caller
2589 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2591 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2592 return true;
2596 * Unlock specific tables
2598 * @param $method String the caller
2600 public function unlockTables( $method ) {
2601 return true;
2605 * Get search engine class. All subclasses of this need to implement this
2606 * if they wish to use searching.
2608 * @return String
2610 public function getSearchEngine() {
2611 return 'SearchEngineDummy';
2615 * Allow or deny "big selects" for this session only. This is done by setting
2616 * the sql_big_selects session variable.
2618 * This is a MySQL-specific feature.
2620 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2622 public function setBigSelects( $value = true ) {
2623 // no-op
2627 /******************************************************************************
2628 * Utility classes
2629 *****************************************************************************/
2632 * Utility class.
2633 * @ingroup Database
2635 class DBObject {
2636 public $mData;
2638 function __construct( $data ) {
2639 $this->mData = $data;
2642 function isLOB() {
2643 return false;
2646 function data() {
2647 return $this->mData;
2652 * Utility class
2653 * @ingroup Database
2655 * This allows us to distinguish a blob from a normal string and an array of strings
2657 class Blob {
2658 private $mData;
2660 function __construct( $data ) {
2661 $this->mData = $data;
2664 function fetch() {
2665 return $this->mData;
2670 * Utility class.
2671 * @ingroup Database
2673 class MySQLField {
2674 private $name, $tablename, $default, $max_length, $nullable,
2675 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2677 function __construct ( $info ) {
2678 $this->name = $info->name;
2679 $this->tablename = $info->table;
2680 $this->default = $info->def;
2681 $this->max_length = $info->max_length;
2682 $this->nullable = !$info->not_null;
2683 $this->is_pk = $info->primary_key;
2684 $this->is_unique = $info->unique_key;
2685 $this->is_multiple = $info->multiple_key;
2686 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
2687 $this->type = $info->type;
2690 function name() {
2691 return $this->name;
2694 function tableName() {
2695 return $this->tableName;
2698 function defaultValue() {
2699 return $this->default;
2702 function maxLength() {
2703 return $this->max_length;
2706 function nullable() {
2707 return $this->nullable;
2710 function isKey() {
2711 return $this->is_key;
2714 function isMultipleKey() {
2715 return $this->is_multiple;
2718 function type() {
2719 return $this->type;
2723 /******************************************************************************
2724 * Error classes
2725 *****************************************************************************/
2728 * Database error base class
2729 * @ingroup Database
2731 class DBError extends MWException {
2732 public $db;
2735 * Construct a database error
2736 * @param $db Database object which threw the error
2737 * @param $error A simple error message to be used for debugging
2739 function __construct( DatabaseBase &$db, $error ) {
2740 $this->db =& $db;
2741 parent::__construct( $error );
2744 function getText() {
2745 global $wgShowDBErrorBacktrace;
2747 $s = $this->getMessage() . "\n";
2749 if ( $wgShowDBErrorBacktrace ) {
2750 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2753 return $s;
2758 * @ingroup Database
2760 class DBConnectionError extends DBError {
2761 public $error;
2763 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2764 $msg = 'DB connection error';
2766 if ( trim( $error ) != '' ) {
2767 $msg .= ": $error";
2770 $this->error = $error;
2772 parent::__construct( $db, $msg );
2775 function useOutputPage() {
2776 // Not likely to work
2777 return false;
2780 function useMessageCache() {
2781 // Not likely to work
2782 return false;
2785 function getLogMessage() {
2786 # Don't send to the exception log
2787 return false;
2790 function getPageTitle() {
2791 global $wgSitename, $wgLang;
2793 $header = "$wgSitename has a problem";
2795 if ( $wgLang instanceof Language ) {
2796 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2799 return $header;
2802 function getHTML() {
2803 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2805 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2806 $again = 'Try waiting a few minutes and reloading.';
2807 $info = '(Can\'t contact the database server: $1)';
2809 if ( $wgLang instanceof Language ) {
2810 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2811 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2812 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2815 # No database access
2816 if ( is_object( $wgMessageCache ) ) {
2817 $wgMessageCache->disable();
2820 if ( trim( $this->error ) == '' ) {
2821 $this->error = $this->db->getProperty( 'mServer' );
2824 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2825 $text = str_replace( '$1', $this->error, $noconnect );
2827 if ( $wgShowDBErrorBacktrace ) {
2828 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2831 $extra = $this->searchForm();
2833 if ( $wgUseFileCache ) {
2834 try {
2835 $cache = $this->fileCachedPage();
2836 # Cached version on file system?
2837 if ( $cache !== null ) {
2838 # Hack: extend the body for error messages
2839 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2840 # Add cache notice...
2841 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2843 # Localize it if possible...
2844 if ( $wgLang instanceof Language ) {
2845 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2848 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2850 # Output cached page with notices on bottom and re-close body
2851 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2853 } catch ( MWException $e ) {
2854 // Do nothing, just use the default page
2858 # Headers needed here - output is just the error message
2859 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2862 function searchForm() {
2863 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2865 $usegoogle = "You can try searching via Google in the meantime.";
2866 $outofdate = "Note that their indexes of our content may be out of date.";
2867 $googlesearch = "Search";
2869 if ( $wgLang instanceof Language ) {
2870 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2871 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2872 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2875 $search = htmlspecialchars( @$_REQUEST['search'] );
2877 $trygoogle = <<<EOT
2878 <div style="margin: 1.5em">$usegoogle<br />
2879 <small>$outofdate</small></div>
2880 <!-- SiteSearch Google -->
2881 <form method="get" action="http://www.google.com/search" id="googlesearch">
2882 <input type="hidden" name="domains" value="$wgServer" />
2883 <input type="hidden" name="num" value="50" />
2884 <input type="hidden" name="ie" value="$wgInputEncoding" />
2885 <input type="hidden" name="oe" value="$wgInputEncoding" />
2887 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2888 <input type="submit" name="btnG" value="$googlesearch" />
2889 <div>
2890 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2891 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2892 </div>
2893 </form>
2894 <!-- SiteSearch Google -->
2895 EOT;
2896 return $trygoogle;
2899 function fileCachedPage() {
2900 global $wgTitle, $title, $wgLang, $wgOut;
2902 if ( $wgOut->isDisabled() ) {
2903 return; // Done already?
2906 $mainpage = 'Main Page';
2908 if ( $wgLang instanceof Language ) {
2909 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2912 if ( $wgTitle ) {
2913 $t =& $wgTitle;
2914 } elseif ( $title ) {
2915 $t = Title::newFromURL( $title );
2916 } else {
2917 $t = Title::newFromText( $mainpage );
2920 $cache = new HTMLFileCache( $t );
2921 if ( $cache->isFileCached() ) {
2922 return $cache->fetchPageText();
2923 } else {
2924 return '';
2928 function htmlBodyOnly() {
2929 return true;
2934 * @ingroup Database
2936 class DBQueryError extends DBError {
2937 public $error, $errno, $sql, $fname;
2939 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2940 $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" .
2941 "Query: $sql\n" .
2942 "Function: $fname\n" .
2943 "Error: $errno $error\n";
2945 parent::__construct( $db, $message );
2947 $this->error = $error;
2948 $this->errno = $errno;
2949 $this->sql = $sql;
2950 $this->fname = $fname;
2953 function getText() {
2954 global $wgShowDBErrorBacktrace;
2956 if ( $this->useMessageCache() ) {
2957 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2958 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2960 if ( $wgShowDBErrorBacktrace ) {
2961 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2964 return $s;
2965 } else {
2966 return parent::getText();
2970 function getSQL() {
2971 global $wgShowSQLErrors;
2973 if ( !$wgShowSQLErrors ) {
2974 return $this->msg( 'sqlhidden', 'SQL hidden' );
2975 } else {
2976 return $this->sql;
2980 function getLogMessage() {
2981 # Don't send to the exception log
2982 return false;
2985 function getPageTitle() {
2986 return $this->msg( 'databaseerror', 'Database error' );
2989 function getHTML() {
2990 global $wgShowDBErrorBacktrace;
2992 if ( $this->useMessageCache() ) {
2993 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2994 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2995 } else {
2996 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2999 if ( $wgShowDBErrorBacktrace ) {
3000 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
3003 return $s;
3008 * @ingroup Database
3010 class DBUnexpectedError extends DBError {}
3014 * Result wrapper for grabbing data queried by someone else
3015 * @ingroup Database
3017 class ResultWrapper implements Iterator {
3018 var $db, $result, $pos = 0, $currentRow = null;
3021 * Create a new result object from a result resource and a Database object
3023 function __construct( $database, $result ) {
3024 $this->db = $database;
3026 if ( $result instanceof ResultWrapper ) {
3027 $this->result = $result->result;
3028 } else {
3029 $this->result = $result;
3034 * Get the number of rows in a result object
3036 function numRows() {
3037 return $this->db->numRows( $this );
3041 * Fetch the next row from the given result object, in object form.
3042 * Fields can be retrieved with $row->fieldname, with fields acting like
3043 * member variables.
3045 * @return MySQL row object
3046 * @throws DBUnexpectedError Thrown if the database returns an error
3048 function fetchObject() {
3049 return $this->db->fetchObject( $this );
3053 * Fetch the next row from the given result object, in associative array
3054 * form. Fields are retrieved with $row['fieldname'].
3056 * @return MySQL row object
3057 * @throws DBUnexpectedError Thrown if the database returns an error
3059 function fetchRow() {
3060 return $this->db->fetchRow( $this );
3064 * Free a result object
3066 function free() {
3067 $this->db->freeResult( $this );
3068 unset( $this->result );
3069 unset( $this->db );
3073 * Change the position of the cursor in a result object
3074 * See mysql_data_seek()
3076 function seek( $row ) {
3077 $this->db->dataSeek( $this, $row );
3080 /*********************
3081 * Iterator functions
3082 * Note that using these in combination with the non-iterator functions
3083 * above may cause rows to be skipped or repeated.
3086 function rewind() {
3087 if ( $this->numRows() ) {
3088 $this->db->dataSeek( $this, 0 );
3090 $this->pos = 0;
3091 $this->currentRow = null;
3094 function current() {
3095 if ( is_null( $this->currentRow ) ) {
3096 $this->next();
3098 return $this->currentRow;
3101 function key() {
3102 return $this->pos;
3105 function next() {
3106 $this->pos++;
3107 $this->currentRow = $this->fetchObject();
3108 return $this->currentRow;
3111 function valid() {
3112 return $this->current() !== false;
3117 * Overloads the relevant methods of the real ResultsWrapper so it
3118 * doesn't go anywhere near an actual database.
3120 class FakeResultWrapper extends ResultWrapper {
3121 var $result = array();
3122 var $db = null; // And it's going to stay that way :D
3123 var $pos = 0;
3124 var $currentRow = null;
3126 function __construct( $array ) {
3127 $this->result = $array;
3130 function numRows() {
3131 return count( $this->result );
3134 function fetchRow() {
3135 $this->currentRow = $this->result[$this->pos++];
3136 return $this->currentRow;
3139 function seek( $row ) {
3140 $this->pos = $row;
3143 function free() {}
3145 // Callers want to be able to access fields with $this->fieldName
3146 function fetchObject() {
3147 $this->currentRow = $this->result[$this->pos++];
3148 return (object)$this->currentRow;
3151 function rewind() {
3152 $this->pos = 0;
3153 $this->currentRow = null;
3158 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3159 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3161 class LikeMatch {
3162 private $str;
3164 public function __construct( $s ) {
3165 $this->str = $s;
3168 public function toString() {
3169 return $this->str;