3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
7 /** Number of times to re-try an operation in case of deadlock */
8 define( 'DEADLOCK_TRIES', 4 );
9 /** Minimum time to wait before retry, in microseconds */
10 define( 'DEADLOCK_DELAY_MIN', 500000 );
11 /** Maximum time to wait before retry */
12 define( 'DEADLOCK_DELAY_MAX', 1500000 );
15 * Database abstraction object
16 * @addtogroup Database
20 #------------------------------------------------------------------------------
22 #------------------------------------------------------------------------------
24 protected $mLastQuery = '';
26 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
27 protected $mOut, $mOpened = false;
29 protected $mFailFunction;
30 protected $mTablePrefix;
32 protected $mTrxLevel = 0;
33 protected $mErrorCount = 0;
34 protected $mLBInfo = array();
35 protected $mFakeSlaveLag = null, $mFakeMaster = false;
37 #------------------------------------------------------------------------------
39 #------------------------------------------------------------------------------
40 # These optionally set a variable and return the previous state
43 * Fail function, takes a Database as a parameter
44 * Set to false for default, 1 for ignore errors
46 function failFunction( $function = NULL ) {
47 return wfSetVar( $this->mFailFunction
, $function );
51 * Output page, used for reporting errors
52 * FALSE means discard output
54 function setOutputPage( $out ) {
59 * Boolean, controls output of large amounts of debug information
61 function debug( $debug = NULL ) {
62 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
66 * Turns buffering of SQL result sets on (true) or off (false).
67 * Default is "on" and it should not be changed without good reasons.
69 function bufferResults( $buffer = NULL ) {
70 if ( is_null( $buffer ) ) {
71 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
73 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
78 * Turns on (false) or off (true) the automatic generation and sending
79 * of a "we're sorry, but there has been a database error" page on
80 * database errors. Default is on (false). When turned off, the
81 * code should use lastErrno() and lastError() to handle the
82 * situation as appropriate.
84 function ignoreErrors( $ignoreErrors = NULL ) {
85 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
89 * The current depth of nested transactions
90 * @param $level Integer: , default NULL.
92 function trxLevel( $level = NULL ) {
93 return wfSetVar( $this->mTrxLevel
, $level );
97 * Number of errors logged, only useful when errors are ignored
99 function errorCount( $count = NULL ) {
100 return wfSetVar( $this->mErrorCount
, $count );
103 function tablePrefix( $prefix = null ) {
104 return wfSetVar( $this->mTablePrefix
, $prefix );
108 * Properties passed down from the server info array of the load balancer
110 function getLBInfo( $name = NULL ) {
111 if ( is_null( $name ) ) {
112 return $this->mLBInfo
;
114 if ( array_key_exists( $name, $this->mLBInfo
) ) {
115 return $this->mLBInfo
[$name];
122 function setLBInfo( $name, $value = NULL ) {
123 if ( is_null( $value ) ) {
124 $this->mLBInfo
= $name;
126 $this->mLBInfo
[$name] = $value;
131 * Set lag time in seconds for a fake slave
133 function setFakeSlaveLag( $lag ) {
134 $this->mFakeSlaveLag
= $lag;
138 * Make this connection a fake master
140 function setFakeMaster( $enabled = true ) {
141 $this->mFakeMaster
= $enabled;
145 * Returns true if this database supports (and uses) cascading deletes
147 function cascadingDeletes() {
152 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
154 function cleanupTriggers() {
159 * Returns true if this database is strict about what can be put into an IP field.
160 * Specifically, it uses a NULL value instead of an empty string.
162 function strictIPs() {
167 * Returns true if this database uses timestamps rather than integers
169 function realTimestamps() {
174 * Returns true if this database does an implicit sort when doing GROUP BY
176 function implicitGroupby() {
181 * Returns true if this database does an implicit order by when the column has an index
182 * For example: SELECT page_title FROM page LIMIT 1
184 function implicitOrderby() {
189 * Returns true if this database can do a native search on IP columns
190 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
192 function searchableIPs() {
197 * Returns true if this database can use functional indexes
199 function functionalIndexes() {
206 function lastQuery() { return $this->mLastQuery
; }
207 function isOpen() { return $this->mOpened
; }
210 function setFlag( $flag ) {
211 $this->mFlags |
= $flag;
214 function clearFlag( $flag ) {
215 $this->mFlags
&= ~
$flag;
218 function getFlag( $flag ) {
219 return !!($this->mFlags
& $flag);
223 * General read-only accessor
225 function getProperty( $name ) {
229 #------------------------------------------------------------------------------
231 #------------------------------------------------------------------------------
235 * @param string $server database server host
236 * @param string $user database user name
237 * @param string $password database user password
238 * @param string $dbname database name
239 * @param failFunction
241 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
243 function __construct( $server = false, $user = false, $password = false, $dbName = false,
244 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
246 global $wgOut, $wgDBprefix, $wgCommandLineMode;
247 # Can't get a reference if it hasn't been set yet
248 if ( !isset( $wgOut ) ) {
251 $this->mOut
=& $wgOut;
253 $this->mFailFunction
= $failFunction;
254 $this->mFlags
= $flags;
256 if ( $this->mFlags
& DBO_DEFAULT
) {
257 if ( $wgCommandLineMode ) {
258 $this->mFlags
&= ~DBO_TRX
;
260 $this->mFlags |
= DBO_TRX
;
265 // Faster read-only access
266 if ( wfReadOnly() ) {
267 $this->mFlags |= DBO_PERSISTENT;
268 $this->mFlags &= ~DBO_TRX;
271 /** Get the default table prefix*/
272 if ( $tablePrefix == 'get from global' ) {
273 $this->mTablePrefix
= $wgDBprefix;
275 $this->mTablePrefix
= $tablePrefix;
279 $this->open( $server, $user, $password, $dbName );
285 * @param failFunction
288 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
290 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
294 * Usually aborts on failure
295 * If the failFunction is set to a non-zero integer, returns success
297 function open( $server, $user, $password, $dbName ) {
298 global $wguname, $wgAllDBsAreLocalhost;
299 wfProfileIn( __METHOD__
);
301 # Test for missing mysql.so
302 # First try to load it
303 if (!@extension_loaded
('mysql')) {
308 # Otherwise we get a suppressed fatal error, which is very hard to track down
309 if ( !function_exists( 'mysql_connect' ) ) {
310 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
313 # Debugging hack -- fake cluster
314 if ( $wgAllDBsAreLocalhost ) {
315 $realServer = 'localhost';
317 $realServer = $server;
320 $this->mServer
= $server;
321 $this->mUser
= $user;
322 $this->mPassword
= $password;
323 $this->mDBname
= $dbName;
327 wfProfileIn("dbconnect-$server");
329 # Try to connect up to three times
330 # The kernel's default SYN retransmission period is far too slow for us,
331 # so we use a short timeout plus a manual retry.
332 $this->mConn
= false;
334 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
338 if ( $this->mFlags
& DBO_PERSISTENT
) {
339 @/**/$this->mConn
= mysql_pconnect( $realServer, $user, $password );
341 # Create a new connection...
342 @/**/$this->mConn
= mysql_connect( $realServer, $user, $password, true );
344 if ($this->mConn
=== false) {
346 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
350 wfProfileOut("dbconnect-$server");
352 if ( $dbName != '' ) {
353 if ( $this->mConn
!== false ) {
354 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
356 $error = "Error selecting database $dbName on server {$this->mServer} " .
357 "from client host {$wguname['nodename']}\n";
358 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
362 wfDebug( "DB connection error\n" );
363 wfDebug( "Server: $server, User: $user, Password: " .
364 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
369 $success = (bool)$this->mConn
;
373 $version = $this->getServerVersion();
374 if ( version_compare( $version, '4.1' ) >= 0 ) {
375 // Tell the server we're communicating with it in UTF-8.
376 // This may engage various charset conversions.
379 $this->query( 'SET NAMES utf8', __METHOD__
);
381 // Turn off strict mode
382 $this->query( "SET sql_mode = ''", __METHOD__
);
385 // Turn off strict mode if it is on
387 $this->reportConnectionError();
390 $this->mOpened
= $success;
391 wfProfileOut( __METHOD__
);
397 * Closes a database connection.
398 * if it is open : commits any open transactions
400 * @return bool operation success. true if already closed.
404 $this->mOpened
= false;
405 if ( $this->mConn
) {
406 if ( $this->trxLevel() ) {
407 $this->immediateCommit();
409 return mysql_close( $this->mConn
);
416 * @param string $error fallback error message, used if none is given by MySQL
418 function reportConnectionError( $error = 'Unknown error' ) {
419 $myError = $this->lastError();
424 if ( $this->mFailFunction
) {
425 # Legacy error handling method
426 if ( !is_int( $this->mFailFunction
) ) {
427 $ff = $this->mFailFunction
;
428 $ff( $this, $error );
432 wfLogDBError( "Connection error: $error\n" );
433 throw new DBConnectionError( $this, $error );
438 * Usually aborts on failure. If errors are explicitly ignored, returns success.
440 * @param $sql String: SQL query
441 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
442 * comment (you can use __METHOD__ or add some extra info)
443 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
444 * maybe best to catch the exception instead?
445 * @return true for a successful write query, ResultWrapper object for a successful read query,
446 * or false on failure if $tempIgnore set
447 * @throws DBQueryError Thrown when the database returns an error of any kind
449 public function query( $sql, $fname = '', $tempIgnore = false ) {
452 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
453 if ( isset( $wgProfiler ) ) {
454 # generalizeSQL will probably cut down the query to reasonable
455 # logging size most of the time. The substr is really just a sanity check.
457 # Who's been wasting my precious column space? -- TS
458 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
461 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
462 $totalProf = 'Database::query-master';
464 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
465 $totalProf = 'Database::query';
467 wfProfileIn( $totalProf );
468 wfProfileIn( $queryProf );
471 $this->mLastQuery
= $sql;
473 # Add a comment for easy SHOW PROCESSLIST interpretation
476 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
477 $userName = $wgUser->getName();
478 if ( mb_strlen( $userName ) > 15 ) {
479 $userName = mb_substr( $userName, 0, 15 ) . '...';
481 $userName = str_replace( '/', '', $userName );
485 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
487 # $commentedSql = $sql;
490 # If DBO_TRX is set, start a transaction
491 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
492 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
493 // avoid establishing transactions for SHOW and SET statements too -
494 // that would delay transaction initializations to once connection
495 // is really used by application
496 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
497 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
501 if ( $this->debug() ) {
502 $sqlx = substr( $commentedSql, 0, 500 );
503 $sqlx = strtr( $sqlx, "\t\n", ' ' );
505 wfDebug( "SQL-master: $sqlx\n" );
507 wfDebug( "SQL: $sqlx\n" );
511 # Do the query and handle errors
512 $ret = $this->doQuery( $commentedSql );
514 # Try reconnecting if the connection was lost
515 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
516 # Transaction is gone, like it or not
517 $this->mTrxLevel
= 0;
518 wfDebug( "Connection lost, reconnecting...\n" );
519 if ( $this->ping() ) {
520 wfDebug( "Reconnected\n" );
521 $sqlx = substr( $commentedSql, 0, 500 );
522 $sqlx = strtr( $sqlx, "\t\n", ' ' );
523 global $wgRequestTime;
524 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
525 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
526 $ret = $this->doQuery( $commentedSql );
528 wfDebug( "Failed\n" );
532 if ( false === $ret ) {
533 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
536 if ( isset( $wgProfiler ) ) {
537 wfProfileOut( $queryProf );
538 wfProfileOut( $totalProf );
540 return $this->resultObject( $ret );
544 * The DBMS-dependent part of query()
545 * @param $sql String: SQL query.
546 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
549 /*private*/ function doQuery( $sql ) {
550 if( $this->bufferResults() ) {
551 $ret = mysql_query( $sql, $this->mConn
);
553 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
562 * @param string $fname
563 * @param bool $tempIgnore
565 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
566 global $wgCommandLineMode;
567 # Ignore errors during error handling to avoid infinite recursion
568 $ignore = $this->ignoreErrors( true );
569 ++
$this->mErrorCount
;
571 if( $ignore ||
$tempIgnore ) {
572 wfDebug("SQL ERROR (ignored): $error\n");
573 $this->ignoreErrors( $ignore );
575 $sql1line = str_replace( "\n", "\\n", $sql );
576 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
577 wfDebug("SQL ERROR: " . $error . "\n");
578 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
584 * Intended to be compatible with the PEAR::DB wrapper functions.
585 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
587 * ? = scalar value, quoted as necessary
588 * ! = raw SQL bit (a function for instance)
589 * & = filename; reads the file and inserts as a blob
590 * (we don't use this though...)
592 function prepare( $sql, $func = 'Database::prepare' ) {
593 /* MySQL doesn't support prepared statements (yet), so just
594 pack up the query for reference. We'll manually replace
596 return array( 'query' => $sql, 'func' => $func );
599 function freePrepared( $prepared ) {
600 /* No-op for MySQL */
604 * Execute a prepared query with the various arguments
605 * @param string $prepared the prepared sql
606 * @param mixed $args Either an array here, or put scalars as varargs
608 function execute( $prepared, $args = null ) {
609 if( !is_array( $args ) ) {
611 $args = func_get_args();
612 array_shift( $args );
614 $sql = $this->fillPrepared( $prepared['query'], $args );
615 return $this->query( $sql, $prepared['func'] );
619 * Prepare & execute an SQL statement, quoting and inserting arguments
620 * in the appropriate places.
621 * @param string $query
622 * @param string $args ...
624 function safeQuery( $query, $args = null ) {
625 $prepared = $this->prepare( $query, 'Database::safeQuery' );
626 if( !is_array( $args ) ) {
628 $args = func_get_args();
629 array_shift( $args );
631 $retval = $this->execute( $prepared, $args );
632 $this->freePrepared( $prepared );
637 * For faking prepared SQL statements on DBs that don't support
639 * @param string $preparedSql - a 'preparable' SQL statement
640 * @param array $args - array of arguments to fill it with
641 * @return string executable SQL
643 function fillPrepared( $preparedQuery, $args ) {
645 $this->preparedArgs
=& $args;
646 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
647 array( &$this, 'fillPreparedArg' ), $preparedQuery );
651 * preg_callback func for fillPrepared()
652 * The arguments should be in $this->preparedArgs and must not be touched
653 * while we're doing this.
655 * @param array $matches
659 function fillPreparedArg( $matches ) {
660 switch( $matches[1] ) {
661 case '\\?': return '?';
662 case '\\!': return '!';
663 case '\\&': return '&';
665 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
666 switch( $matches[1] ) {
667 case '?': return $this->addQuotes( $arg );
668 case '!': return $arg;
670 # return $this->addQuotes( file_get_contents( $arg ) );
671 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
673 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
678 * @param mixed $res A SQL result
681 * Free a result object
683 function freeResult( $res ) {
684 if ( $res instanceof ResultWrapper
) {
687 if ( !@/**/mysql_free_result( $res ) ) {
688 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
693 * Fetch the next row from the given result object, in object form.
694 * Fields can be retrieved with $row->fieldname, with fields acting like
697 * @param $res SQL result object as returned from Database::query(), etc.
698 * @return MySQL row object
699 * @throws DBUnexpectedError Thrown if the database returns an error
701 function fetchObject( $res ) {
702 if ( $res instanceof ResultWrapper
) {
705 @/**/$row = mysql_fetch_object( $res );
706 if( $this->lastErrno() ) {
707 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
713 * Fetch the next row from the given result object, in associative array
714 * form. Fields are retrieved with $row['fieldname'].
716 * @param $res SQL result object as returned from Database::query(), etc.
717 * @return MySQL row object
718 * @throws DBUnexpectedError Thrown if the database returns an error
720 function fetchRow( $res ) {
721 if ( $res instanceof ResultWrapper
) {
724 @/**/$row = mysql_fetch_array( $res );
725 if ( $this->lastErrno() ) {
726 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
732 * Get the number of rows in a result object
734 function numRows( $res ) {
735 if ( $res instanceof ResultWrapper
) {
738 @/**/$n = mysql_num_rows( $res );
739 if( $this->lastErrno() ) {
740 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
746 * Get the number of fields in a result object
747 * See documentation for mysql_num_fields()
749 function numFields( $res ) {
750 if ( $res instanceof ResultWrapper
) {
753 return mysql_num_fields( $res );
757 * Get a field name in a result object
758 * See documentation for mysql_field_name():
759 * http://www.php.net/mysql_field_name
761 function fieldName( $res, $n ) {
762 if ( $res instanceof ResultWrapper
) {
765 return mysql_field_name( $res, $n );
769 * Get the inserted value of an auto-increment row
771 * The value inserted should be fetched from nextSequenceValue()
774 * $id = $dbw->nextSequenceValue('page_page_id_seq');
775 * $dbw->insert('page',array('page_id' => $id));
776 * $id = $dbw->insertId();
778 function insertId() { return mysql_insert_id( $this->mConn
); }
781 * Change the position of the cursor in a result object
782 * See mysql_data_seek()
784 function dataSeek( $res, $row ) {
785 if ( $res instanceof ResultWrapper
) {
788 return mysql_data_seek( $res, $row );
792 * Get the last error number
795 function lastErrno() {
796 if ( $this->mConn
) {
797 return mysql_errno( $this->mConn
);
799 return mysql_errno();
804 * Get a description of the last error
805 * See mysql_error() for more details
807 function lastError() {
808 if ( $this->mConn
) {
809 # Even if it's non-zero, it can still be invalid
810 wfSuppressWarnings();
811 $error = mysql_error( $this->mConn
);
813 $error = mysql_error();
817 $error = mysql_error();
820 $error .= ' (' . $this->mServer
. ')';
825 * Get the number of rows affected by the last write query
826 * See mysql_affected_rows() for more details
828 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
829 /**#@-*/ // end of template : @param $result
832 * Simple UPDATE wrapper
833 * Usually aborts on failure
834 * If errors are explicitly ignored, returns success
836 * This function exists for historical reasons, Database::update() has a more standard
837 * calling convention and feature set
839 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
841 $table = $this->tableName( $table );
842 $sql = "UPDATE $table SET $var = '" .
843 $this->strencode( $value ) . "' WHERE ($cond)";
844 return (bool)$this->query( $sql, $fname );
848 * Simple SELECT wrapper, returns a single field, input must be encoded
849 * Usually aborts on failure
850 * If errors are explicitly ignored, returns FALSE on failure
852 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
853 if ( !is_array( $options ) ) {
854 $options = array( $options );
856 $options['LIMIT'] = 1;
858 $res = $this->select( $table, $var, $cond, $fname, $options );
859 if ( $res === false ||
!$this->numRows( $res ) ) {
862 $row = $this->fetchRow( $res );
863 if ( $row !== false ) {
864 $this->freeResult( $res );
872 * Returns an optional USE INDEX clause to go after the table, and a
873 * string to go at the end of the query
877 * @param array $options an associative array of options to be turned into
878 * an SQL query, valid keys are listed in the function.
881 function makeSelectOptions( $options ) {
882 $preLimitTail = $postLimitTail = '';
885 $noKeyOptions = array();
886 foreach ( $options as $key => $option ) {
887 if ( is_numeric( $key ) ) {
888 $noKeyOptions[$option] = true;
892 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
893 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
894 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
896 //if (isset($options['LIMIT'])) {
897 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
898 // isset($options['OFFSET']) ? $options['OFFSET']
902 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
903 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
904 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
906 # Various MySQL extensions
907 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
908 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
909 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
910 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
911 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
912 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
913 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
914 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
916 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
917 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
922 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
928 * @param mixed $table Array or string, table name(s) (prefix auto-added)
929 * @param mixed $vars Array or string, field name(s) to be retrieved
930 * @param mixed $conds Array or string, condition(s) for WHERE
931 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
932 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
933 * see Database::makeSelectOptions code for list of supported stuff
934 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
936 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
938 if( is_array( $vars ) ) {
939 $vars = implode( ',', $vars );
941 if( !is_array( $options ) ) {
942 $options = array( $options );
944 if( is_array( $table ) ) {
945 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
946 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
948 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
949 } elseif ($table!='') {
950 if ($table{0}==' ') {
951 $from = ' FROM ' . $table;
953 $from = ' FROM ' . $this->tableName( $table );
959 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
961 if( !empty( $conds ) ) {
962 if ( is_array( $conds ) ) {
963 $conds = $this->makeList( $conds, LIST_AND
);
965 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
967 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
970 if (isset($options['LIMIT']))
971 $sql = $this->limitResult($sql, $options['LIMIT'],
972 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
973 $sql = "$sql $postLimitTail";
975 if (isset($options['EXPLAIN'])) {
976 $sql = 'EXPLAIN ' . $sql;
978 return $this->query( $sql, $fname );
982 * Single row SELECT wrapper
983 * Aborts or returns FALSE on error
985 * $vars: the selected variables
986 * $conds: a condition map, terms are ANDed together.
987 * Items with numeric keys are taken to be literal conditions
988 * Takes an array of selected variables, and a condition map, which is ANDed
989 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
990 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
991 * $obj- >page_id is the ID of the Astronomy article
993 * @todo migrate documentation to phpdocumentor format
995 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
996 $options['LIMIT'] = 1;
997 $res = $this->select( $table, $vars, $conds, $fname, $options );
998 if ( $res === false )
1000 if ( !$this->numRows($res) ) {
1001 $this->freeResult($res);
1004 $obj = $this->fetchObject( $res );
1005 $this->freeResult( $res );
1011 * Estimate rows in dataset
1012 * Returns estimated count, based on EXPLAIN output
1013 * Takes same arguments as Database::select()
1016 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1017 $options['EXPLAIN']=true;
1018 $res = $this->select ($table, $vars, $conds, $fname, $options );
1019 if ( $res === false )
1021 if (!$this->numRows($res)) {
1022 $this->freeResult($res);
1028 while( $plan = $this->fetchObject( $res ) ) {
1029 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1032 $this->freeResult($res);
1038 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1039 * It's only slightly flawed. Don't use for anything important.
1041 * @param string $sql A SQL Query
1044 static function generalizeSQL( $sql ) {
1045 # This does the same as the regexp below would do, but in such a way
1046 # as to avoid crashing php on some large strings.
1047 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1049 $sql = str_replace ( "\\\\", '', $sql);
1050 $sql = str_replace ( "\\'", '', $sql);
1051 $sql = str_replace ( "\\\"", '', $sql);
1052 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1053 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1055 # All newlines, tabs, etc replaced by single space
1056 $sql = preg_replace ( '/\s+/', ' ', $sql);
1059 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1065 * Determines whether a field exists in a table
1066 * Usually aborts on failure
1067 * If errors are explicitly ignored, returns NULL on failure
1069 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1070 $table = $this->tableName( $table );
1071 $res = $this->query( 'DESCRIBE '.$table, $fname );
1078 while ( $row = $this->fetchObject( $res ) ) {
1079 if ( $row->Field
== $field ) {
1088 * Determines whether an index exists
1089 * Usually aborts on failure
1090 * If errors are explicitly ignored, returns NULL on failure
1092 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1093 $info = $this->indexInfo( $table, $index, $fname );
1094 if ( is_null( $info ) ) {
1097 return $info !== false;
1103 * Get information about an index into an object
1104 * Returns false if the index does not exist
1106 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1107 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1108 # SHOW INDEX should work for 3.x and up:
1109 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1110 $table = $this->tableName( $table );
1111 $sql = 'SHOW INDEX FROM '.$table;
1112 $res = $this->query( $sql, $fname );
1118 while ( $row = $this->fetchObject( $res ) ) {
1119 if ( $row->Key_name
== $index ) {
1123 $this->freeResult($res);
1125 return empty($result) ?
false : $result;
1129 * Query whether a given table exists
1131 function tableExists( $table ) {
1132 $table = $this->tableName( $table );
1133 $old = $this->ignoreErrors( true );
1134 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1135 $this->ignoreErrors( $old );
1137 $this->freeResult( $res );
1145 * mysql_fetch_field() wrapper
1146 * Returns false if the field doesn't exist
1151 function fieldInfo( $table, $field ) {
1152 $table = $this->tableName( $table );
1153 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1154 $n = mysql_num_fields( $res->result
);
1155 for( $i = 0; $i < $n; $i++
) {
1156 $meta = mysql_fetch_field( $res->result
, $i );
1157 if( $field == $meta->name
) {
1158 return new MySQLField($meta);
1165 * mysql_field_type() wrapper
1167 function fieldType( $res, $index ) {
1168 if ( $res instanceof ResultWrapper
) {
1169 $res = $res->result
;
1171 return mysql_field_type( $res, $index );
1175 * Determines if a given index is unique
1177 function indexUnique( $table, $index ) {
1178 $indexInfo = $this->indexInfo( $table, $index );
1179 if ( !$indexInfo ) {
1182 return !$indexInfo[0]->Non_unique
;
1186 * INSERT wrapper, inserts an array into a table
1188 * $a may be a single associative array, or an array of these with numeric keys, for
1191 * Usually aborts on failure
1192 * If errors are explicitly ignored, returns success
1194 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1195 # No rows to insert, easy just return now
1196 if ( !count( $a ) ) {
1200 $table = $this->tableName( $table );
1201 if ( !is_array( $options ) ) {
1202 $options = array( $options );
1204 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1206 $keys = array_keys( $a[0] );
1209 $keys = array_keys( $a );
1212 $sql = 'INSERT ' . implode( ' ', $options ) .
1213 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1217 foreach ( $a as $row ) {
1223 $sql .= '(' . $this->makeList( $row ) . ')';
1226 $sql .= '(' . $this->makeList( $a ) . ')';
1228 return (bool)$this->query( $sql, $fname );
1232 * Make UPDATE options for the Database::update function
1235 * @param array $options The options passed to Database::update
1238 function makeUpdateOptions( $options ) {
1239 if( !is_array( $options ) ) {
1240 $options = array( $options );
1243 if ( in_array( 'LOW_PRIORITY', $options ) )
1244 $opts[] = $this->lowPriorityOption();
1245 if ( in_array( 'IGNORE', $options ) )
1247 return implode(' ', $opts);
1251 * UPDATE wrapper, takes a condition array and a SET array
1253 * @param string $table The table to UPDATE
1254 * @param array $values An array of values to SET
1255 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1256 * @param string $fname The Class::Function calling this function
1258 * @param array $options An array of UPDATE options, can be one or
1259 * more of IGNORE, LOW_PRIORITY
1262 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1263 $table = $this->tableName( $table );
1264 $opts = $this->makeUpdateOptions( $options );
1265 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1266 if ( $conds != '*' ) {
1267 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1269 return $this->query( $sql, $fname );
1273 * Makes an encoded list of strings from an array
1275 * LIST_COMMA - comma separated, no field names
1276 * LIST_AND - ANDed WHERE clause (without the WHERE)
1277 * LIST_OR - ORed WHERE clause (without the WHERE)
1278 * LIST_SET - comma separated with field names, like a SET clause
1279 * LIST_NAMES - comma separated field names
1281 function makeList( $a, $mode = LIST_COMMA
) {
1282 if ( !is_array( $a ) ) {
1283 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1288 foreach ( $a as $field => $value ) {
1290 if ( $mode == LIST_AND
) {
1292 } elseif($mode == LIST_OR
) {
1300 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1301 $list .= "($value)";
1302 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1304 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1305 if( count( $value ) == 0 ) {
1306 throw new MWException( __METHOD__
.': empty input' );
1307 } elseif( count( $value ) == 1 ) {
1308 // Special-case single values, as IN isn't terribly efficient
1309 // Don't necessarily assume the single key is 0; we don't
1310 // enforce linear numeric ordering on other arrays here.
1311 $value = array_values( $value );
1312 $list .= $field." = ".$this->addQuotes( $value[0] );
1314 $list .= $field." IN (".$this->makeList($value).") ";
1316 } elseif( is_null($value) ) {
1317 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1318 $list .= "$field IS ";
1319 } elseif ( $mode == LIST_SET
) {
1320 $list .= "$field = ";
1324 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1325 $list .= "$field = ";
1327 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1334 * Change the current database
1336 function selectDB( $db ) {
1337 $this->mDBname
= $db;
1338 return mysql_select_db( $db, $this->mConn
);
1342 * Get the current DB name
1344 function getDBname() {
1345 return $this->mDBname
;
1349 * Get the server hostname or IP address
1351 function getServer() {
1352 return $this->mServer
;
1356 * Format a table name ready for use in constructing an SQL query
1358 * This does two important things: it quotes the table names to clean them up,
1359 * and it adds a table prefix if only given a table name with no quotes.
1361 * All functions of this object which require a table name call this function
1362 * themselves. Pass the canonical name to such functions. This is only needed
1363 * when calling query() directly.
1365 * @param string $name database table name
1366 * @return string full database name
1368 function tableName( $name ) {
1369 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1370 # Skip the entire process when we have a string quoted on both ends.
1371 # Note that we check the end so that we will still quote any use of
1372 # use of `database`.table. But won't break things if someone wants
1373 # to query a database table with a dot in the name.
1374 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1376 # Lets test for any bits of text that should never show up in a table
1377 # name. Basically anything like JOIN or ON which are actually part of
1378 # SQL queries, but may end up inside of the table value to combine
1379 # sql. Such as how the API is doing.
1380 # Note that we use a whitespace test rather than a \b test to avoid
1381 # any remote case where a word like on may be inside of a table name
1382 # surrounded by symbols which may be considered word breaks.
1383 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1385 # Split database and table into proper variables.
1386 # We reverse the explode so that database.table and table both output
1387 # the correct table.
1388 @list
( $table, $database ) = array_reverse( explode( '.', $name, 2 ) );
1389 $prefix = $this->mTablePrefix
; # Default prefix
1391 # A database name has been specified in input. Quote the table name
1392 # because we don't want any prefixes added.
1393 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1395 # Note that we use the long format because php will complain in in_array if
1396 # the input is not an array, and will complain in is_array if it is not set.
1397 if( !isset( $database ) # Don't use shared database if pre selected.
1398 && isset( $wgSharedDB ) # We have a shared database
1399 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1400 && isset( $wgSharedTables )
1401 && is_array( $wgSharedTables )
1402 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1403 $database = $wgSharedDB;
1404 $prefix = isset( $wgSharedprefix ) ?
$wgSharedprefix : $prefix;
1407 # Quote the $database and $table and apply the prefix if not quoted.
1408 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1409 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1411 # Merge our database and table into our final table name.
1412 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1414 # We're finished, return.
1419 * Fetch a number of table names into an array
1420 * This is handy when you need to construct SQL for joins
1423 * extract($dbr->tableNames('user','watchlist'));
1424 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1425 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1427 public function tableNames() {
1428 $inArray = func_get_args();
1430 foreach ( $inArray as $name ) {
1431 $retVal[$name] = $this->tableName( $name );
1437 * Fetch a number of table names into an zero-indexed numerical array
1438 * This is handy when you need to construct SQL for joins
1441 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1442 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1443 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1445 public function tableNamesN() {
1446 $inArray = func_get_args();
1448 foreach ( $inArray as $name ) {
1449 $retVal[] = $this->tableName( $name );
1457 function tableNamesWithUseIndex( $tables, $use_index ) {
1460 foreach ( $tables as $table )
1461 if ( @$use_index[$table] !== null )
1462 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1464 $ret[] = $this->tableName( $table );
1466 return implode( ',', $ret );
1470 * Wrapper for addslashes()
1471 * @param string $s String to be slashed.
1472 * @return string slashed string.
1474 function strencode( $s ) {
1475 return mysql_real_escape_string( $s, $this->mConn
);
1479 * If it's a string, adds quotes and backslashes
1480 * Otherwise returns as-is
1482 function addQuotes( $s ) {
1483 if ( is_null( $s ) ) {
1486 # This will also quote numeric values. This should be harmless,
1487 # and protects against weird problems that occur when they really
1488 # _are_ strings such as article titles and string->number->string
1489 # conversion is not 1:1.
1490 return "'" . $this->strencode( $s ) . "'";
1495 * Escape string for safe LIKE usage
1497 function escapeLike( $s ) {
1498 $s=$this->strencode( $s );
1499 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1504 * Returns an appropriately quoted sequence value for inserting a new row.
1505 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1506 * subclass will return an integer, and save the value for insertId()
1508 function nextSequenceValue( $seqName ) {
1514 * PostgreSQL doesn't have them and returns ""
1516 function useIndexClause( $index ) {
1517 return "FORCE INDEX ($index)";
1521 * REPLACE query wrapper
1522 * PostgreSQL simulates this with a DELETE followed by INSERT
1523 * $row is the row to insert, an associative array
1524 * $uniqueIndexes is an array of indexes. Each element may be either a
1525 * field name or an array of field names
1527 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1528 * However if you do this, you run the risk of encountering errors which wouldn't have
1531 * @todo migrate comment to phodocumentor format
1533 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1534 $table = $this->tableName( $table );
1537 if ( !is_array( reset( $rows ) ) ) {
1538 $rows = array( $rows );
1541 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1543 foreach ( $rows as $row ) {
1549 $sql .= '(' . $this->makeList( $row ) . ')';
1551 return $this->query( $sql, $fname );
1555 * DELETE where the condition is a join
1556 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1558 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1559 * join condition matches, set $conds='*'
1561 * DO NOT put the join condition in $conds
1563 * @param string $delTable The table to delete from.
1564 * @param string $joinTable The other table.
1565 * @param string $delVar The variable to join on, in the first table.
1566 * @param string $joinVar The variable to join on, in the second table.
1567 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1569 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1571 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1574 $delTable = $this->tableName( $delTable );
1575 $joinTable = $this->tableName( $joinTable );
1576 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1577 if ( $conds != '*' ) {
1578 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1581 return $this->query( $sql, $fname );
1585 * Returns the size of a text field, or -1 for "unlimited"
1587 function textFieldSize( $table, $field ) {
1588 $table = $this->tableName( $table );
1589 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1590 $res = $this->query( $sql, 'Database::textFieldSize' );
1591 $row = $this->fetchObject( $res );
1592 $this->freeResult( $res );
1595 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1604 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1606 function lowPriorityOption() {
1607 return 'LOW_PRIORITY';
1611 * DELETE query wrapper
1613 * Use $conds == "*" to delete all rows
1615 function delete( $table, $conds, $fname = 'Database::delete' ) {
1617 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1619 $table = $this->tableName( $table );
1620 $sql = "DELETE FROM $table";
1621 if ( $conds != '*' ) {
1622 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1624 return $this->query( $sql, $fname );
1628 * INSERT SELECT wrapper
1629 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1630 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1631 * $conds may be "*" to copy the whole table
1632 * srcTable may be an array of tables.
1634 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1635 $insertOptions = array(), $selectOptions = array() )
1637 $destTable = $this->tableName( $destTable );
1638 if ( is_array( $insertOptions ) ) {
1639 $insertOptions = implode( ' ', $insertOptions );
1641 if( !is_array( $selectOptions ) ) {
1642 $selectOptions = array( $selectOptions );
1644 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1645 if( is_array( $srcTable ) ) {
1646 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1648 $srcTable = $this->tableName( $srcTable );
1650 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1651 " SELECT $startOpts " . implode( ',', $varMap ) .
1652 " FROM $srcTable $useIndex ";
1653 if ( $conds != '*' ) {
1654 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1656 $sql .= " $tailOpts";
1657 return $this->query( $sql, $fname );
1661 * Construct a LIMIT query with optional offset
1662 * This is used for query pages
1663 * $sql string SQL query we will append the limit too
1664 * $limit integer the SQL limit
1665 * $offset integer the SQL offset (default false)
1667 function limitResult($sql, $limit, $offset=false) {
1668 if( !is_numeric($limit) ) {
1669 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1671 return "$sql LIMIT "
1672 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1675 function limitResultForUpdate($sql, $num) {
1676 return $this->limitResult($sql, $num, 0);
1680 * Returns an SQL expression for a simple conditional.
1683 * @param string $cond SQL expression which will result in a boolean value
1684 * @param string $trueVal SQL expression to return if true
1685 * @param string $falseVal SQL expression to return if false
1686 * @return string SQL fragment
1688 function conditional( $cond, $trueVal, $falseVal ) {
1689 return " IF($cond, $trueVal, $falseVal) ";
1693 * Returns a comand for str_replace function in SQL query.
1694 * Uses REPLACE() in MySQL
1696 * @param string $orig String or column to modify
1697 * @param string $old String or column to seek
1698 * @param string $new String or column to replace with
1700 function strreplace( $orig, $old, $new ) {
1701 return "REPLACE({$orig}, {$old}, {$new})";
1705 * Determines if the last failure was due to a deadlock
1707 function wasDeadlock() {
1708 return $this->lastErrno() == 1213;
1712 * Perform a deadlock-prone transaction.
1714 * This function invokes a callback function to perform a set of write
1715 * queries. If a deadlock occurs during the processing, the transaction
1716 * will be rolled back and the callback function will be called again.
1719 * $dbw->deadlockLoop( callback, ... );
1721 * Extra arguments are passed through to the specified callback function.
1723 * Returns whatever the callback function returned on its successful,
1724 * iteration, or false on error, for example if the retry limit was
1727 function deadlockLoop() {
1728 $myFname = 'Database::deadlockLoop';
1731 $args = func_get_args();
1732 $function = array_shift( $args );
1733 $oldIgnore = $this->ignoreErrors( true );
1734 $tries = DEADLOCK_TRIES
;
1735 if ( is_array( $function ) ) {
1736 $fname = $function[0];
1741 $retVal = call_user_func_array( $function, $args );
1742 $error = $this->lastError();
1743 $errno = $this->lastErrno();
1744 $sql = $this->lastQuery();
1747 if ( $this->wasDeadlock() ) {
1749 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1751 $this->reportQueryError( $error, $errno, $sql, $fname );
1754 } while( $this->wasDeadlock() && --$tries > 0 );
1755 $this->ignoreErrors( $oldIgnore );
1756 if ( $tries <= 0 ) {
1757 $this->query( 'ROLLBACK', $myFname );
1758 $this->reportQueryError( $error, $errno, $sql, $fname );
1761 $this->query( 'COMMIT', $myFname );
1767 * Do a SELECT MASTER_POS_WAIT()
1769 * @param string $file the binlog file
1770 * @param string $pos the binlog position
1771 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1773 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1774 $fname = 'Database::masterPosWait';
1775 wfProfileIn( $fname );
1777 # Commit any open transactions
1778 if ( $this->mTrxLevel
) {
1779 $this->immediateCommit();
1782 if ( !is_null( $this->mFakeSlaveLag
) ) {
1783 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1784 if ( $wait > $timeout * 1e6
) {
1785 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1786 wfProfileOut( $fname );
1788 } elseif ( $wait > 0 ) {
1789 wfDebug( "Fake slave waiting $wait us\n" );
1791 wfProfileOut( $fname );
1794 wfDebug( "Fake slave up to date ($wait us)\n" );
1795 wfProfileOut( $fname );
1800 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1801 $encFile = $this->addQuotes( $pos->file
);
1802 $encPos = intval( $pos->pos
);
1803 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1804 $res = $this->doQuery( $sql );
1805 if ( $res && $row = $this->fetchRow( $res ) ) {
1806 $this->freeResult( $res );
1807 wfProfileOut( $fname );
1810 wfProfileOut( $fname );
1816 * Get the position of the master from SHOW SLAVE STATUS
1818 function getSlavePos() {
1819 if ( !is_null( $this->mFakeSlaveLag
) ) {
1820 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1821 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1824 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1825 $row = $this->fetchObject( $res );
1827 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1834 * Get the position of the master from SHOW MASTER STATUS
1836 function getMasterPos() {
1837 if ( $this->mFakeMaster
) {
1838 return new MySQLMasterPos( 'fake', microtime( true ) );
1840 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1841 $row = $this->fetchObject( $res );
1843 return new MySQLMasterPos( $row->File
, $row->Position
);
1850 * Begin a transaction, committing any previously open transaction
1852 function begin( $fname = 'Database::begin' ) {
1853 $this->query( 'BEGIN', $fname );
1854 $this->mTrxLevel
= 1;
1860 function commit( $fname = 'Database::commit' ) {
1861 $this->query( 'COMMIT', $fname );
1862 $this->mTrxLevel
= 0;
1866 * Rollback a transaction.
1867 * No-op on non-transactional databases.
1869 function rollback( $fname = 'Database::rollback' ) {
1870 $this->query( 'ROLLBACK', $fname, true );
1871 $this->mTrxLevel
= 0;
1875 * Begin a transaction, committing any previously open transaction
1876 * @deprecated use begin()
1878 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1883 * Commit transaction, if one is open
1884 * @deprecated use commit()
1886 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1891 * Return MW-style timestamp used for MySQL schema
1893 function timestamp( $ts=0 ) {
1894 return wfTimestamp(TS_MW
,$ts);
1898 * Local database timestamp format or null
1900 function timestampOrNull( $ts = null ) {
1901 if( is_null( $ts ) ) {
1904 return $this->timestamp( $ts );
1911 function resultObject( $result ) {
1912 if( empty( $result ) ) {
1914 } elseif ( $result instanceof ResultWrapper
) {
1916 } elseif ( $result === true ) {
1917 // Successful write query
1920 return new ResultWrapper( $this, $result );
1925 * Return aggregated value alias
1927 function aggregateValue ($valuedata,$valuename='value') {
1932 * @return string wikitext of a link to the server software's web site
1934 function getSoftwareLink() {
1935 return "[http://www.mysql.com/ MySQL]";
1939 * @return string Version information from the database
1941 function getServerVersion() {
1942 return mysql_get_server_info( $this->mConn
);
1946 * Ping the server and try to reconnect if it there is no connection
1949 if( !function_exists( 'mysql_ping' ) ) {
1950 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1953 $ping = mysql_ping( $this->mConn
);
1958 // Need to reconnect manually in MySQL client 5.0.13+
1959 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
1960 mysql_close( $this->mConn
);
1961 $this->mOpened
= false;
1962 $this->mConn
= false;
1963 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
1971 * At the moment, this will only work if the DB user has the PROCESS privilege
1974 if ( !is_null( $this->mFakeSlaveLag
) ) {
1975 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
1976 return $this->mFakeSlaveLag
;
1978 $res = $this->query( 'SHOW PROCESSLIST' );
1979 # Find slave SQL thread
1980 while ( $row = $this->fetchObject( $res ) ) {
1981 /* This should work for most situations - when default db
1982 * for thread is not specified, it had no events executed,
1983 * and therefore it doesn't know yet how lagged it is.
1985 * Relay log I/O thread does not select databases.
1987 if ( $row->User
== 'system user' &&
1988 $row->State
!= 'Waiting for master to send event' &&
1989 $row->State
!= 'Connecting to master' &&
1990 $row->State
!= 'Queueing master event to the relay log' &&
1991 $row->State
!= 'Waiting for master update' &&
1992 $row->State
!= 'Requesting binlog dump'
1994 # This is it, return the time (except -ve)
1995 if ( $row->Time
> 0x7fffffff ) {
2006 * Get status information from SHOW STATUS in an associative array
2008 function getStatus($which="%") {
2009 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2011 while ( $row = $this->fetchObject( $res ) ) {
2012 $status[$row->Variable_name
] = $row->Value
;
2018 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2020 function maxListLen() {
2024 function encodeBlob($b) {
2028 function decodeBlob($b) {
2033 * Override database's default connection timeout.
2034 * May be useful for very long batch queries such as
2035 * full-wiki dumps, where a single query reads out
2036 * over hours or days.
2037 * @param int $timeout in seconds
2039 public function setTimeout( $timeout ) {
2040 $this->query( "SET net_read_timeout=$timeout" );
2041 $this->query( "SET net_write_timeout=$timeout" );
2045 * Read and execute SQL commands from a file.
2046 * Returns true on success, error string on failure
2047 * @param string $filename File name to open
2048 * @param callback $lineCallback Optional function called before reading each line
2049 * @param callback $resultCallback Optional function called for each MySQL result
2051 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2052 $fp = fopen( $filename, 'r' );
2053 if ( false === $fp ) {
2054 return "Could not open \"{$filename}\".\n";
2056 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2062 * Read and execute commands from an open file handle
2063 * Returns true on success, error string on failure
2064 * @param string $fp File handle
2065 * @param callback $lineCallback Optional function called before reading each line
2066 * @param callback $resultCallback Optional function called for each MySQL result
2068 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2071 $dollarquote = false;
2073 while ( ! feof( $fp ) ) {
2074 if ( $lineCallback ) {
2075 call_user_func( $lineCallback );
2077 $line = trim( fgets( $fp, 1024 ) );
2078 $sl = strlen( $line ) - 1;
2080 if ( $sl < 0 ) { continue; }
2081 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2083 ## Allow dollar quoting for function declarations
2084 if (substr($line,0,4) == '$mw$') {
2086 $dollarquote = false;
2090 $dollarquote = true;
2093 else if (!$dollarquote) {
2094 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2096 $line = substr( $line, 0, $sl );
2100 if ( '' != $cmd ) { $cmd .= ' '; }
2104 $cmd = str_replace(';;', ";", $cmd);
2105 $cmd = $this->replaceVars( $cmd );
2106 $res = $this->query( $cmd, __METHOD__
, true );
2107 if ( $resultCallback ) {
2108 call_user_func( $resultCallback, $res );
2111 if ( false === $res ) {
2112 $err = $this->lastError();
2113 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2125 * Replace variables in sourced SQL
2127 protected function replaceVars( $ins ) {
2129 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2130 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2131 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2134 // Ordinary variables
2135 foreach ( $varnames as $var ) {
2136 if( isset( $GLOBALS[$var] ) ) {
2137 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2138 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2139 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2140 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2145 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2146 array( &$this, 'tableNameCallback' ), $ins );
2151 * Table name callback
2154 protected function tableNameCallback( $matches ) {
2155 return $this->tableName( $matches[1] );
2159 * Build a concatenation list to feed into a SQL query
2161 function buildConcat( $stringList ) {
2162 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2168 * Database abstraction object for mySQL
2169 * Inherit all methods and properties of Database::Database()
2171 * @addtogroup Database
2174 class DatabaseMysql
extends Database
{
2178 /******************************************************************************
2180 *****************************************************************************/
2184 * @addtogroup Database
2189 function DBObject($data) {
2190 $this->mData
= $data;
2198 return $this->mData
;
2204 * @addtogroup Database
2206 * This allows us to distinguish a blob from a normal string and an array of strings
2210 function __construct($data) {
2211 $this->mData
= $data;
2214 return $this->mData
;
2220 * @addtogroup Database
2223 private $name, $tablename, $default, $max_length, $nullable,
2224 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2225 function __construct ($info) {
2226 $this->name
= $info->name
;
2227 $this->tablename
= $info->table
;
2228 $this->default = $info->def
;
2229 $this->max_length
= $info->max_length
;
2230 $this->nullable
= !$info->not_null
;
2231 $this->is_pk
= $info->primary_key
;
2232 $this->is_unique
= $info->unique_key
;
2233 $this->is_multiple
= $info->multiple_key
;
2234 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2235 $this->type
= $info->type
;
2242 function tableName() {
2243 return $this->tableName
;
2246 function defaultValue() {
2247 return $this->default;
2250 function maxLength() {
2251 return $this->max_length
;
2254 function nullable() {
2255 return $this->nullable
;
2259 return $this->is_key
;
2262 function isMultipleKey() {
2263 return $this->is_multiple
;
2271 /******************************************************************************
2273 *****************************************************************************/
2276 * Database error base class
2277 * @addtogroup Database
2279 class DBError
extends MWException
{
2283 * Construct a database error
2284 * @param Database $db The database object which threw the error
2285 * @param string $error A simple error message to be used for debugging
2287 function __construct( Database
&$db, $error ) {
2289 parent
::__construct( $error );
2294 * @addtogroup Database
2296 class DBConnectionError
extends DBError
{
2299 function __construct( Database
&$db, $error = 'unknown error' ) {
2300 $msg = 'DB connection error';
2301 if ( trim( $error ) != '' ) {
2304 $this->error
= $error;
2305 parent
::__construct( $db, $msg );
2308 function useOutputPage() {
2309 // Not likely to work
2313 function useMessageCache() {
2314 // Not likely to work
2318 function getText() {
2319 return $this->getMessage() . "\n";
2322 function getLogMessage() {
2323 # Don't send to the exception log
2327 function getPageTitle() {
2329 return "$wgSitename has a problem";
2332 function getHTML() {
2333 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2334 global $wgSitename, $wgServer, $wgMessageCache;
2336 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2337 # Hard coding strings instead.
2339 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2340 $mainpage = 'Main Page';
2341 $searchdisabled = <<<EOT
2342 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2343 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2347 <!-- SiteSearch Google -->
2348 <FORM method=GET action=\"http://www.google.com/search\">
2349 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2350 <A HREF=\"http://www.google.com/\">
2351 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2352 border=\"0\" ALT=\"Google\"></A>
2355 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2356 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2358 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
2359 <input type='hidden' name='ie' value='$2'>
2360 <input type='hidden' name='oe' value='$2'>
2364 <!-- SiteSearch Google -->";
2365 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2367 # No database access
2368 if ( is_object( $wgMessageCache ) ) {
2369 $wgMessageCache->disable();
2372 if ( trim( $this->error
) == '' ) {
2373 $this->error
= $this->db
->getProperty('mServer');
2376 $text = str_replace( '$1', $this->error
, $noconnect );
2377 $text .= wfGetSiteNotice();
2379 if($wgUseFileCache) {
2384 $t = Title
::newFromURL( $title );
2385 } elseif (@/**/$_REQUEST['search']) {
2386 $search = $_REQUEST['search'];
2387 return $searchdisabled .
2388 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2389 $wgInputEncoding ), $googlesearch );
2391 $t = Title
::newFromText( $mainpage );
2395 $cache = new HTMLFileCache( $t );
2396 if( $cache->isFileCached() ) {
2397 // @todo, FIXME: $msg is not defined on the next line.
2398 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2399 $cachederror . "</b></p>\n";
2401 $tag = '<div id="article">';
2402 $text = str_replace(
2405 $cache->fetchPageText() );
2414 * @addtogroup Database
2416 class DBQueryError
extends DBError
{
2417 public $error, $errno, $sql, $fname;
2419 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2420 $message = "A database error has occurred\n" .
2422 "Function: $fname\n" .
2423 "Error: $errno $error\n";
2425 parent
::__construct( $db, $message );
2426 $this->error
= $error;
2427 $this->errno
= $errno;
2429 $this->fname
= $fname;
2432 function getText() {
2433 if ( $this->useMessageCache() ) {
2434 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2435 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2437 return $this->getMessage();
2442 global $wgShowSQLErrors;
2443 if( !$wgShowSQLErrors ) {
2444 return $this->msg( 'sqlhidden', 'SQL hidden' );
2450 function getLogMessage() {
2451 # Don't send to the exception log
2455 function getPageTitle() {
2456 return $this->msg( 'databaseerror', 'Database error' );
2459 function getHTML() {
2460 if ( $this->useMessageCache() ) {
2461 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2462 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2464 return nl2br( htmlspecialchars( $this->getMessage() ) );
2470 * @addtogroup Database
2472 class DBUnexpectedError
extends DBError
{}
2476 * Result wrapper for grabbing data queried by someone else
2477 * @addtogroup Database
2479 class ResultWrapper
implements Iterator
{
2480 var $db, $result, $pos = 0, $currentRow = null;
2483 * Create a new result object from a result resource and a Database object
2485 function ResultWrapper( $database, $result ) {
2486 $this->db
= $database;
2487 if ( $result instanceof ResultWrapper
) {
2488 $this->result
= $result->result
;
2490 $this->result
= $result;
2495 * Get the number of rows in a result object
2497 function numRows() {
2498 return $this->db
->numRows( $this->result
);
2502 * Fetch the next row from the given result object, in object form.
2503 * Fields can be retrieved with $row->fieldname, with fields acting like
2506 * @param $res SQL result object as returned from Database::query(), etc.
2507 * @return MySQL row object
2508 * @throws DBUnexpectedError Thrown if the database returns an error
2510 function fetchObject() {
2511 return $this->db
->fetchObject( $this->result
);
2515 * Fetch the next row from the given result object, in associative array
2516 * form. Fields are retrieved with $row['fieldname'].
2518 * @param $res SQL result object as returned from Database::query(), etc.
2519 * @return MySQL row object
2520 * @throws DBUnexpectedError Thrown if the database returns an error
2522 function fetchRow() {
2523 return $this->db
->fetchRow( $this->result
);
2527 * Free a result object
2530 $this->db
->freeResult( $this->result
);
2531 unset( $this->result
);
2536 * Change the position of the cursor in a result object
2537 * See mysql_data_seek()
2539 function seek( $row ) {
2540 $this->db
->dataSeek( $this->result
, $row );
2543 /*********************
2544 * Iterator functions
2545 * Note that using these in combination with the non-iterator functions
2546 * above may cause rows to be skipped or repeated.
2550 if ($this->numRows()) {
2551 $this->db
->dataSeek($this->result
, 0);
2554 $this->currentRow
= null;
2557 function current() {
2558 if ( is_null( $this->currentRow
) ) {
2561 return $this->currentRow
;
2570 $this->currentRow
= $this->fetchObject();
2571 return $this->currentRow
;
2575 return $this->current() !== false;
2579 class MySQLMasterPos
{
2582 function __construct( $file, $pos ) {
2583 $this->file
= $file;
2587 function __toString() {
2588 return "{$this->file}/{$this->pos}";