Change new section summary to use /* blah */ format to match section editing look...
[mediawiki.git] / includes / Database.php
blob4f8c7d5e10aa915e29666087156322e3880a2b88
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 */
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 );
14 /******************************************************************************
15 * Utility classes
16 *****************************************************************************/
18 /**
19 * Utility class.
20 * @addtogroup Database
22 class DBObject {
23 public $mData;
25 function DBObject($data) {
26 $this->mData = $data;
29 function isLOB() {
30 return false;
33 function data() {
34 return $this->mData;
38 /**
39 * Utility class.
40 * @addtogroup Database
42 class MySQLField {
43 private $name, $tablename, $default, $max_length, $nullable,
44 $is_pk, $is_unique, $is_key, $type;
45 function __construct ($info) {
46 $this->name = $info->name;
47 $this->tablename = $info->table;
48 $this->default = $info->def;
49 $this->max_length = $info->max_length;
50 $this->nullable = !$info->not_null;
51 $this->is_pk = $info->primary_key;
52 $this->is_unique = $info->unique_key;
53 $this->is_multiple = $info->multiple_key;
54 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
55 $this->type = $info->type;
58 function name() {
59 return $this->name;
62 function tableName() {
63 return $this->tableName;
66 function defaultValue() {
67 return $this->default;
70 function maxLength() {
71 return $this->max_length;
74 function nullable() {
75 return $this->nullable;
78 function isKey() {
79 return $this->is_key;
82 function isMultipleKey() {
83 return $this->is_multiple;
86 function type() {
87 return $this->type;
91 /******************************************************************************
92 * Error classes
93 *****************************************************************************/
95 /**
96 * Database error base class
97 * @addtogroup Database
99 class DBError extends MWException {
100 public $db;
103 * Construct a database error
104 * @param Database $db The database object which threw the error
105 * @param string $error A simple error message to be used for debugging
107 function __construct( Database &$db, $error ) {
108 $this->db =& $db;
109 parent::__construct( $error );
114 * @addtogroup Database
116 class DBConnectionError extends DBError {
117 public $error;
119 function __construct( Database &$db, $error = 'unknown error' ) {
120 $msg = 'DB connection error';
121 if ( trim( $error ) != '' ) {
122 $msg .= ": $error";
124 $this->error = $error;
125 parent::__construct( $db, $msg );
128 function useOutputPage() {
129 // Not likely to work
130 return false;
133 function useMessageCache() {
134 // Not likely to work
135 return false;
138 function getText() {
139 return $this->getMessage() . "\n";
142 function getLogMessage() {
143 # Don't send to the exception log
144 return false;
147 function getPageTitle() {
148 global $wgSitename;
149 return "$wgSitename has a problem";
152 function getHTML() {
153 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
154 global $wgSitename, $wgServer, $wgMessageCache;
156 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
157 # Hard coding strings instead.
159 $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>";
160 $mainpage = 'Main Page';
161 $searchdisabled = <<<EOT
162 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
163 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
164 EOT;
166 $googlesearch = "
167 <!-- SiteSearch Google -->
168 <FORM method=GET action=\"http://www.google.com/search\">
169 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
170 <A HREF=\"http://www.google.com/\">
171 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
172 border=\"0\" ALT=\"Google\"></A>
173 </td>
174 <td>
175 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
176 <INPUT type=submit name=btnG VALUE=\"Google Search\">
177 <font size=-1>
178 <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 />
179 <input type='hidden' name='ie' value='$2'>
180 <input type='hidden' name='oe' value='$2'>
181 </font>
182 </td></tr></TABLE>
183 </FORM>
184 <!-- SiteSearch Google -->";
185 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
187 # No database access
188 if ( is_object( $wgMessageCache ) ) {
189 $wgMessageCache->disable();
192 if ( trim( $this->error ) == '' ) {
193 $this->error = $this->db->getProperty('mServer');
196 $text = str_replace( '$1', $this->error, $noconnect );
197 $text .= wfGetSiteNotice();
199 if($wgUseFileCache) {
200 if($wgTitle) {
201 $t =& $wgTitle;
202 } else {
203 if($title) {
204 $t = Title::newFromURL( $title );
205 } elseif (@/**/$_REQUEST['search']) {
206 $search = $_REQUEST['search'];
207 return $searchdisabled .
208 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
209 $wgInputEncoding ), $googlesearch );
210 } else {
211 $t = Title::newFromText( $mainpage );
215 $cache = new HTMLFileCache( $t );
216 if( $cache->isFileCached() ) {
217 // @todo, FIXME: $msg is not defined on the next line.
218 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
219 $cachederror . "</b></p>\n";
221 $tag = '<div id="article">';
222 $text = str_replace(
223 $tag,
224 $tag . $msg,
225 $cache->fetchPageText() );
229 return $text;
234 * @addtogroup Database
236 class DBQueryError extends DBError {
237 public $error, $errno, $sql, $fname;
239 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
240 $message = "A database error has occurred\n" .
241 "Query: $sql\n" .
242 "Function: $fname\n" .
243 "Error: $errno $error\n";
245 parent::__construct( $db, $message );
246 $this->error = $error;
247 $this->errno = $errno;
248 $this->sql = $sql;
249 $this->fname = $fname;
252 function getText() {
253 if ( $this->useMessageCache() ) {
254 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
255 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
256 } else {
257 return $this->getMessage();
261 function getSQL() {
262 global $wgShowSQLErrors;
263 if( !$wgShowSQLErrors ) {
264 return $this->msg( 'sqlhidden', 'SQL hidden' );
265 } else {
266 return $this->sql;
270 function getLogMessage() {
271 # Don't send to the exception log
272 return false;
275 function getPageTitle() {
276 return $this->msg( 'databaseerror', 'Database error' );
279 function getHTML() {
280 if ( $this->useMessageCache() ) {
281 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
282 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
283 } else {
284 return nl2br( htmlspecialchars( $this->getMessage() ) );
290 * @addtogroup Database
292 class DBUnexpectedError extends DBError {}
294 /******************************************************************************/
297 * Database abstraction object
298 * @addtogroup Database
300 class Database {
302 #------------------------------------------------------------------------------
303 # Variables
304 #------------------------------------------------------------------------------
306 protected $mLastQuery = '';
308 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
309 protected $mOut, $mOpened = false;
311 protected $mFailFunction;
312 protected $mTablePrefix;
313 protected $mFlags;
314 protected $mTrxLevel = 0;
315 protected $mErrorCount = 0;
316 protected $mLBInfo = array();
318 #------------------------------------------------------------------------------
319 # Accessors
320 #------------------------------------------------------------------------------
321 # These optionally set a variable and return the previous state
324 * Fail function, takes a Database as a parameter
325 * Set to false for default, 1 for ignore errors
327 function failFunction( $function = NULL ) {
328 return wfSetVar( $this->mFailFunction, $function );
332 * Output page, used for reporting errors
333 * FALSE means discard output
335 function setOutputPage( $out ) {
336 $this->mOut = $out;
340 * Boolean, controls output of large amounts of debug information
342 function debug( $debug = NULL ) {
343 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
347 * Turns buffering of SQL result sets on (true) or off (false).
348 * Default is "on" and it should not be changed without good reasons.
350 function bufferResults( $buffer = NULL ) {
351 if ( is_null( $buffer ) ) {
352 return !(bool)( $this->mFlags & DBO_NOBUFFER );
353 } else {
354 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
359 * Turns on (false) or off (true) the automatic generation and sending
360 * of a "we're sorry, but there has been a database error" page on
361 * database errors. Default is on (false). When turned off, the
362 * code should use lastErrno() and lastError() to handle the
363 * situation as appropriate.
365 function ignoreErrors( $ignoreErrors = NULL ) {
366 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
370 * The current depth of nested transactions
371 * @param $level Integer: , default NULL.
373 function trxLevel( $level = NULL ) {
374 return wfSetVar( $this->mTrxLevel, $level );
378 * Number of errors logged, only useful when errors are ignored
380 function errorCount( $count = NULL ) {
381 return wfSetVar( $this->mErrorCount, $count );
385 * Properties passed down from the server info array of the load balancer
387 function getLBInfo( $name = NULL ) {
388 if ( is_null( $name ) ) {
389 return $this->mLBInfo;
390 } else {
391 if ( array_key_exists( $name, $this->mLBInfo ) ) {
392 return $this->mLBInfo[$name];
393 } else {
394 return NULL;
399 function setLBInfo( $name, $value = NULL ) {
400 if ( is_null( $value ) ) {
401 $this->mLBInfo = $name;
402 } else {
403 $this->mLBInfo[$name] = $value;
408 * Returns true if this database supports (and uses) cascading deletes
410 function cascadingDeletes() {
411 return false;
415 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
417 function cleanupTriggers() {
418 return false;
422 * Returns true if this database is strict about what can be put into an IP field.
423 * Specifically, it uses a NULL value instead of an empty string.
425 function strictIPs() {
426 return false;
430 * Returns true if this database uses timestamps rather than integers
432 function realTimestamps() {
433 return false;
437 * Returns true if this database does an implicit sort when doing GROUP BY
439 function implicitGroupby() {
440 return true;
444 * Returns true if this database does an implicit order by when the column has an index
445 * For example: SELECT page_title FROM page LIMIT 1
447 function implicitOrderby() {
448 return true;
452 * Returns true if this database can do a native search on IP columns
453 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
455 function searchableIPs() {
456 return false;
460 * Returns true if this database can use functional indexes
462 function functionalIndexes() {
463 return false;
466 /**#@+
467 * Get function
469 function lastQuery() { return $this->mLastQuery; }
470 function isOpen() { return $this->mOpened; }
471 /**#@-*/
473 function setFlag( $flag ) {
474 $this->mFlags |= $flag;
477 function clearFlag( $flag ) {
478 $this->mFlags &= ~$flag;
481 function getFlag( $flag ) {
482 return !!($this->mFlags & $flag);
486 * General read-only accessor
488 function getProperty( $name ) {
489 return $this->$name;
492 #------------------------------------------------------------------------------
493 # Other functions
494 #------------------------------------------------------------------------------
496 /**@{{
497 * Constructor.
498 * @param string $server database server host
499 * @param string $user database user name
500 * @param string $password database user password
501 * @param string $dbname database name
502 * @param failFunction
503 * @param $flags
504 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
506 function __construct( $server = false, $user = false, $password = false, $dbName = false,
507 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
509 global $wgOut, $wgDBprefix, $wgCommandLineMode;
510 # Can't get a reference if it hasn't been set yet
511 if ( !isset( $wgOut ) ) {
512 $wgOut = NULL;
514 $this->mOut =& $wgOut;
516 $this->mFailFunction = $failFunction;
517 $this->mFlags = $flags;
519 if ( $this->mFlags & DBO_DEFAULT ) {
520 if ( $wgCommandLineMode ) {
521 $this->mFlags &= ~DBO_TRX;
522 } else {
523 $this->mFlags |= DBO_TRX;
528 // Faster read-only access
529 if ( wfReadOnly() ) {
530 $this->mFlags |= DBO_PERSISTENT;
531 $this->mFlags &= ~DBO_TRX;
534 /** Get the default table prefix*/
535 if ( $tablePrefix == 'get from global' ) {
536 $this->mTablePrefix = $wgDBprefix;
537 } else {
538 $this->mTablePrefix = $tablePrefix;
541 if ( $server ) {
542 $this->open( $server, $user, $password, $dbName );
547 * @static
548 * @param failFunction
549 * @param $flags
551 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
553 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
557 * Usually aborts on failure
558 * If the failFunction is set to a non-zero integer, returns success
560 function open( $server, $user, $password, $dbName ) {
561 global $wguname;
562 wfProfileIn( __METHOD__ );
564 # Test for missing mysql.so
565 # First try to load it
566 if (!@extension_loaded('mysql')) {
567 @dl('mysql.so');
570 # Fail now
571 # Otherwise we get a suppressed fatal error, which is very hard to track down
572 if ( !function_exists( 'mysql_connect' ) ) {
573 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
576 $this->close();
577 $this->mServer = $server;
578 $this->mUser = $user;
579 $this->mPassword = $password;
580 $this->mDBname = $dbName;
582 $success = false;
584 wfProfileIn("dbconnect-$server");
586 # LIVE PATCH by Tim, ask Domas for why: retry loop
587 $this->mConn = false;
588 $max = 3;
589 for ( $i = 0; $i < $max && !$this->mConn; $i++ ) {
590 if ( $i > 1 ) {
591 usleep( 1000 );
593 if ( $this->mFlags & DBO_PERSISTENT ) {
594 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
595 } else {
596 # Create a new connection...
597 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
599 if ($this->mConn === false) {
600 #$iplus = $i + 1;
601 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
605 wfProfileOut("dbconnect-$server");
607 if ( $dbName != '' ) {
608 if ( $this->mConn !== false ) {
609 $success = @/**/mysql_select_db( $dbName, $this->mConn );
610 if ( !$success ) {
611 $error = "Error selecting database $dbName on server {$this->mServer} " .
612 "from client host {$wguname['nodename']}\n";
613 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
614 wfDebug( $error );
616 } else {
617 wfDebug( "DB connection error\n" );
618 wfDebug( "Server: $server, User: $user, Password: " .
619 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
620 $success = false;
622 } else {
623 # Delay USE query
624 $success = (bool)$this->mConn;
627 if ( $success ) {
628 $version = $this->getServerVersion();
629 if ( version_compare( $version, '4.1' ) >= 0 ) {
630 // Tell the server we're communicating with it in UTF-8.
631 // This may engage various charset conversions.
632 global $wgDBmysql5;
633 if( $wgDBmysql5 ) {
634 $this->query( 'SET NAMES utf8', __METHOD__ );
636 // Turn off strict mode
637 $this->query( "SET sql_mode = ''", __METHOD__ );
640 // Turn off strict mode if it is on
641 } else {
642 $this->reportConnectionError();
645 $this->mOpened = $success;
646 wfProfileOut( __METHOD__ );
647 return $success;
649 /**@}}*/
652 * Closes a database connection.
653 * if it is open : commits any open transactions
655 * @return bool operation success. true if already closed.
657 function close()
659 $this->mOpened = false;
660 if ( $this->mConn ) {
661 if ( $this->trxLevel() ) {
662 $this->immediateCommit();
664 return mysql_close( $this->mConn );
665 } else {
666 return true;
671 * @param string $error fallback error message, used if none is given by MySQL
673 function reportConnectionError( $error = 'Unknown error' ) {
674 $myError = $this->lastError();
675 if ( $myError ) {
676 $error = $myError;
679 if ( $this->mFailFunction ) {
680 # Legacy error handling method
681 if ( !is_int( $this->mFailFunction ) ) {
682 $ff = $this->mFailFunction;
683 $ff( $this, $error );
685 } else {
686 # New method
687 wfLogDBError( "Connection error: $error\n" );
688 throw new DBConnectionError( $this, $error );
693 * Usually aborts on failure. If errors are explicitly ignored, returns success.
695 * @param $sql String: SQL query
696 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
697 * comment (you can use __METHOD__ or add some extra info)
698 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
699 * maybe best to catch the exception instead?
700 * @return true for a successful write query, ResultWrapper object for a successful read query,
701 * or false on failure if $tempIgnore set
702 * @throws DBQueryError Thrown when the database returns an error of any kind
704 public function query( $sql, $fname = '', $tempIgnore = false ) {
705 global $wgProfiling;
707 if ( $wgProfiling ) {
708 # generalizeSQL will probably cut down the query to reasonable
709 # logging size most of the time. The substr is really just a sanity check.
711 # Who's been wasting my precious column space? -- TS
712 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
714 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
715 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
716 $totalProf = 'Database::query';
717 } else {
718 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
719 $totalProf = 'Database::query-master';
721 wfProfileIn( $totalProf );
722 wfProfileIn( $queryProf );
725 $this->mLastQuery = $sql;
727 # Add a comment for easy SHOW PROCESSLIST interpretation
728 #if ( $fname ) {
729 global $wgUser;
730 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
731 $userName = $wgUser->getName();
732 if ( strlen( $userName ) > 15 ) {
733 $userName = substr( $userName, 0, 15 ) . '...';
735 $userName = str_replace( '/', '', $userName );
736 } else {
737 $userName = '';
739 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
740 #} else {
741 # $commentedSql = $sql;
744 # If DBO_TRX is set, start a transaction
745 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
746 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
748 $this->begin();
751 if ( $this->debug() ) {
752 $sqlx = substr( $commentedSql, 0, 500 );
753 $sqlx = strtr( $sqlx, "\t\n", ' ' );
754 wfDebug( "SQL: $sqlx\n" );
757 # Do the query and handle errors
758 $ret = $this->doQuery( $commentedSql );
760 # Try reconnecting if the connection was lost
761 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
762 # Transaction is gone, like it or not
763 $this->mTrxLevel = 0;
764 wfDebug( "Connection lost, reconnecting...\n" );
765 if ( $this->ping() ) {
766 wfDebug( "Reconnected\n" );
767 $sqlx = substr( $commentedSql, 0, 500 );
768 $sqlx = strtr( $sqlx, "\t\n", ' ' );
769 global $wgRequestTime;
770 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
771 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
772 $ret = $this->doQuery( $commentedSql );
773 } else {
774 wfDebug( "Failed\n" );
778 if ( false === $ret ) {
779 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
782 if ( $wgProfiling ) {
783 wfProfileOut( $queryProf );
784 wfProfileOut( $totalProf );
786 return $this->resultObject( $ret );
790 * The DBMS-dependent part of query()
791 * @param $sql String: SQL query.
792 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
793 * @access private
795 /*private*/ function doQuery( $sql ) {
796 if( $this->bufferResults() ) {
797 $ret = mysql_query( $sql, $this->mConn );
798 } else {
799 $ret = mysql_unbuffered_query( $sql, $this->mConn );
801 return $ret;
805 * @param $error
806 * @param $errno
807 * @param $sql
808 * @param string $fname
809 * @param bool $tempIgnore
811 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
812 global $wgCommandLineMode;
813 # Ignore errors during error handling to avoid infinite recursion
814 $ignore = $this->ignoreErrors( true );
815 ++$this->mErrorCount;
817 if( $ignore || $tempIgnore ) {
818 wfDebug("SQL ERROR (ignored): $error\n");
819 $this->ignoreErrors( $ignore );
820 } else {
821 $sql1line = str_replace( "\n", "\\n", $sql );
822 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
823 wfDebug("SQL ERROR: " . $error . "\n");
824 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
830 * Intended to be compatible with the PEAR::DB wrapper functions.
831 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
833 * ? = scalar value, quoted as necessary
834 * ! = raw SQL bit (a function for instance)
835 * & = filename; reads the file and inserts as a blob
836 * (we don't use this though...)
838 function prepare( $sql, $func = 'Database::prepare' ) {
839 /* MySQL doesn't support prepared statements (yet), so just
840 pack up the query for reference. We'll manually replace
841 the bits later. */
842 return array( 'query' => $sql, 'func' => $func );
845 function freePrepared( $prepared ) {
846 /* No-op for MySQL */
850 * Execute a prepared query with the various arguments
851 * @param string $prepared the prepared sql
852 * @param mixed $args Either an array here, or put scalars as varargs
854 function execute( $prepared, $args = null ) {
855 if( !is_array( $args ) ) {
856 # Pull the var args
857 $args = func_get_args();
858 array_shift( $args );
860 $sql = $this->fillPrepared( $prepared['query'], $args );
861 return $this->query( $sql, $prepared['func'] );
865 * Prepare & execute an SQL statement, quoting and inserting arguments
866 * in the appropriate places.
867 * @param string $query
868 * @param string $args ...
870 function safeQuery( $query, $args = null ) {
871 $prepared = $this->prepare( $query, 'Database::safeQuery' );
872 if( !is_array( $args ) ) {
873 # Pull the var args
874 $args = func_get_args();
875 array_shift( $args );
877 $retval = $this->execute( $prepared, $args );
878 $this->freePrepared( $prepared );
879 return $retval;
883 * For faking prepared SQL statements on DBs that don't support
884 * it directly.
885 * @param string $preparedSql - a 'preparable' SQL statement
886 * @param array $args - array of arguments to fill it with
887 * @return string executable SQL
889 function fillPrepared( $preparedQuery, $args ) {
890 reset( $args );
891 $this->preparedArgs =& $args;
892 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
893 array( &$this, 'fillPreparedArg' ), $preparedQuery );
897 * preg_callback func for fillPrepared()
898 * The arguments should be in $this->preparedArgs and must not be touched
899 * while we're doing this.
901 * @param array $matches
902 * @return string
903 * @private
905 function fillPreparedArg( $matches ) {
906 switch( $matches[1] ) {
907 case '\\?': return '?';
908 case '\\!': return '!';
909 case '\\&': return '&';
911 list( /* $n */ , $arg ) = each( $this->preparedArgs );
912 switch( $matches[1] ) {
913 case '?': return $this->addQuotes( $arg );
914 case '!': return $arg;
915 case '&':
916 # return $this->addQuotes( file_get_contents( $arg ) );
917 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
918 default:
919 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
923 /**#@+
924 * @param mixed $res A SQL result
927 * Free a result object
929 function freeResult( $res ) {
930 if ( $res instanceof ResultWrapper ) {
931 $res = $res->result;
933 if ( !@/**/mysql_free_result( $res ) ) {
934 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
939 * Fetch the next row from the given result object, in object form.
940 * Fields can be retrieved with $row->fieldname, with fields acting like
941 * member variables.
943 * @param $res SQL result object as returned from Database::query(), etc.
944 * @return MySQL row object
945 * @throws DBUnexpectedError Thrown if the database returns an error
947 function fetchObject( $res ) {
948 if ( $res instanceof ResultWrapper ) {
949 $res = $res->result;
951 @/**/$row = mysql_fetch_object( $res );
952 if( $this->lastErrno() ) {
953 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
955 return $row;
959 * Fetch the next row from the given result object, in associative array
960 * form. Fields are retrieved with $row['fieldname'].
962 * @param $res SQL result object as returned from Database::query(), etc.
963 * @return MySQL row object
964 * @throws DBUnexpectedError Thrown if the database returns an error
966 function fetchRow( $res ) {
967 if ( $res instanceof ResultWrapper ) {
968 $res = $res->result;
970 @/**/$row = mysql_fetch_array( $res );
971 if ( $this->lastErrno() ) {
972 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
974 return $row;
978 * Get the number of rows in a result object
980 function numRows( $res ) {
981 if ( $res instanceof ResultWrapper ) {
982 $res = $res->result;
984 @/**/$n = mysql_num_rows( $res );
985 if( $this->lastErrno() ) {
986 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
988 return $n;
992 * Get the number of fields in a result object
993 * See documentation for mysql_num_fields()
995 function numFields( $res ) {
996 if ( $res instanceof ResultWrapper ) {
997 $res = $res->result;
999 return mysql_num_fields( $res );
1003 * Get a field name in a result object
1004 * See documentation for mysql_field_name():
1005 * http://www.php.net/mysql_field_name
1007 function fieldName( $res, $n ) {
1008 if ( $res instanceof ResultWrapper ) {
1009 $res = $res->result;
1011 return mysql_field_name( $res, $n );
1015 * Get the inserted value of an auto-increment row
1017 * The value inserted should be fetched from nextSequenceValue()
1019 * Example:
1020 * $id = $dbw->nextSequenceValue('page_page_id_seq');
1021 * $dbw->insert('page',array('page_id' => $id));
1022 * $id = $dbw->insertId();
1024 function insertId() { return mysql_insert_id( $this->mConn ); }
1027 * Change the position of the cursor in a result object
1028 * See mysql_data_seek()
1030 function dataSeek( $res, $row ) {
1031 if ( $res instanceof ResultWrapper ) {
1032 $res = $res->result;
1034 return mysql_data_seek( $res, $row );
1038 * Get the last error number
1039 * See mysql_errno()
1041 function lastErrno() {
1042 if ( $this->mConn ) {
1043 return mysql_errno( $this->mConn );
1044 } else {
1045 return mysql_errno();
1050 * Get a description of the last error
1051 * See mysql_error() for more details
1053 function lastError() {
1054 if ( $this->mConn ) {
1055 # Even if it's non-zero, it can still be invalid
1056 wfSuppressWarnings();
1057 $error = mysql_error( $this->mConn );
1058 if ( !$error ) {
1059 $error = mysql_error();
1061 wfRestoreWarnings();
1062 } else {
1063 $error = mysql_error();
1065 if( $error ) {
1066 $error .= ' (' . $this->mServer . ')';
1068 return $error;
1071 * Get the number of rows affected by the last write query
1072 * See mysql_affected_rows() for more details
1074 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
1075 /**#@-*/ // end of template : @param $result
1078 * Simple UPDATE wrapper
1079 * Usually aborts on failure
1080 * If errors are explicitly ignored, returns success
1082 * This function exists for historical reasons, Database::update() has a more standard
1083 * calling convention and feature set
1085 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1087 $table = $this->tableName( $table );
1088 $sql = "UPDATE $table SET $var = '" .
1089 $this->strencode( $value ) . "' WHERE ($cond)";
1090 return (bool)$this->query( $sql, $fname );
1094 * Simple SELECT wrapper, returns a single field, input must be encoded
1095 * Usually aborts on failure
1096 * If errors are explicitly ignored, returns FALSE on failure
1098 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1099 if ( !is_array( $options ) ) {
1100 $options = array( $options );
1102 $options['LIMIT'] = 1;
1104 $res = $this->select( $table, $var, $cond, $fname, $options );
1105 if ( $res === false || !$this->numRows( $res ) ) {
1106 return false;
1108 $row = $this->fetchRow( $res );
1109 if ( $row !== false ) {
1110 $this->freeResult( $res );
1111 return $row[0];
1112 } else {
1113 return false;
1118 * Returns an optional USE INDEX clause to go after the table, and a
1119 * string to go at the end of the query
1121 * @private
1123 * @param array $options an associative array of options to be turned into
1124 * an SQL query, valid keys are listed in the function.
1125 * @return array
1127 function makeSelectOptions( $options ) {
1128 $preLimitTail = $postLimitTail = '';
1129 $startOpts = '';
1131 $noKeyOptions = array();
1132 foreach ( $options as $key => $option ) {
1133 if ( is_numeric( $key ) ) {
1134 $noKeyOptions[$option] = true;
1138 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1139 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1140 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1142 //if (isset($options['LIMIT'])) {
1143 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1144 // isset($options['OFFSET']) ? $options['OFFSET']
1145 // : false);
1148 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1149 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1150 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1152 # Various MySQL extensions
1153 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1154 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1155 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1156 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1157 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1158 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1159 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1160 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1162 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1163 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1164 } else {
1165 $useIndex = '';
1168 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1172 * SELECT wrapper
1174 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1175 * @param mixed $vars Array or string, field name(s) to be retrieved
1176 * @param mixed $conds Array or string, condition(s) for WHERE
1177 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1178 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1179 * see Database::makeSelectOptions code for list of supported stuff
1180 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1182 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1184 if( is_array( $vars ) ) {
1185 $vars = implode( ',', $vars );
1187 if( !is_array( $options ) ) {
1188 $options = array( $options );
1190 if( is_array( $table ) ) {
1191 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1192 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1193 else
1194 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1195 } elseif ($table!='') {
1196 if ($table{0}==' ') {
1197 $from = ' FROM ' . $table;
1198 } else {
1199 $from = ' FROM ' . $this->tableName( $table );
1201 } else {
1202 $from = '';
1205 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1207 if( !empty( $conds ) ) {
1208 if ( is_array( $conds ) ) {
1209 $conds = $this->makeList( $conds, LIST_AND );
1211 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1212 } else {
1213 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1216 if (isset($options['LIMIT']))
1217 $sql = $this->limitResult($sql, $options['LIMIT'],
1218 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1219 $sql = "$sql $postLimitTail";
1221 if (isset($options['EXPLAIN'])) {
1222 $sql = 'EXPLAIN ' . $sql;
1224 return $this->query( $sql, $fname );
1228 * Single row SELECT wrapper
1229 * Aborts or returns FALSE on error
1231 * $vars: the selected variables
1232 * $conds: a condition map, terms are ANDed together.
1233 * Items with numeric keys are taken to be literal conditions
1234 * Takes an array of selected variables, and a condition map, which is ANDed
1235 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1236 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1237 * $obj- >page_id is the ID of the Astronomy article
1239 * @todo migrate documentation to phpdocumentor format
1241 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1242 $options['LIMIT'] = 1;
1243 $res = $this->select( $table, $vars, $conds, $fname, $options );
1244 if ( $res === false )
1245 return false;
1246 if ( !$this->numRows($res) ) {
1247 $this->freeResult($res);
1248 return false;
1250 $obj = $this->fetchObject( $res );
1251 $this->freeResult( $res );
1252 return $obj;
1257 * Estimate rows in dataset
1258 * Returns estimated count, based on EXPLAIN output
1259 * Takes same arguments as Database::select()
1262 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1263 $options['EXPLAIN']=true;
1264 $res = $this->select ($table, $vars, $conds, $fname, $options );
1265 if ( $res === false )
1266 return false;
1267 if (!$this->numRows($res)) {
1268 $this->freeResult($res);
1269 return 0;
1272 $rows=1;
1274 while( $plan = $this->fetchObject( $res ) ) {
1275 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1278 $this->freeResult($res);
1279 return $rows;
1284 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1285 * It's only slightly flawed. Don't use for anything important.
1287 * @param string $sql A SQL Query
1288 * @static
1290 static function generalizeSQL( $sql ) {
1291 # This does the same as the regexp below would do, but in such a way
1292 # as to avoid crashing php on some large strings.
1293 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1295 $sql = str_replace ( "\\\\", '', $sql);
1296 $sql = str_replace ( "\\'", '', $sql);
1297 $sql = str_replace ( "\\\"", '', $sql);
1298 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1299 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1301 # All newlines, tabs, etc replaced by single space
1302 $sql = preg_replace ( '/\s+/', ' ', $sql);
1304 # All numbers => N
1305 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1307 return $sql;
1311 * Determines whether a field exists in a table
1312 * Usually aborts on failure
1313 * If errors are explicitly ignored, returns NULL on failure
1315 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1316 $table = $this->tableName( $table );
1317 $res = $this->query( 'DESCRIBE '.$table, $fname );
1318 if ( !$res ) {
1319 return NULL;
1322 $found = false;
1324 while ( $row = $this->fetchObject( $res ) ) {
1325 if ( $row->Field == $field ) {
1326 $found = true;
1327 break;
1330 return $found;
1334 * Determines whether an index exists
1335 * Usually aborts on failure
1336 * If errors are explicitly ignored, returns NULL on failure
1338 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1339 $info = $this->indexInfo( $table, $index, $fname );
1340 if ( is_null( $info ) ) {
1341 return NULL;
1342 } else {
1343 return $info !== false;
1349 * Get information about an index into an object
1350 * Returns false if the index does not exist
1352 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1353 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1354 # SHOW INDEX should work for 3.x and up:
1355 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1356 $table = $this->tableName( $table );
1357 $sql = 'SHOW INDEX FROM '.$table;
1358 $res = $this->query( $sql, $fname );
1359 if ( !$res ) {
1360 return NULL;
1363 $result = array();
1364 while ( $row = $this->fetchObject( $res ) ) {
1365 if ( $row->Key_name == $index ) {
1366 $result[] = $row;
1369 $this->freeResult($res);
1371 return empty($result) ? false : $result;
1375 * Query whether a given table exists
1377 function tableExists( $table ) {
1378 $table = $this->tableName( $table );
1379 $old = $this->ignoreErrors( true );
1380 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1381 $this->ignoreErrors( $old );
1382 if( $res ) {
1383 $this->freeResult( $res );
1384 return true;
1385 } else {
1386 return false;
1391 * mysql_fetch_field() wrapper
1392 * Returns false if the field doesn't exist
1394 * @param $table
1395 * @param $field
1397 function fieldInfo( $table, $field ) {
1398 $table = $this->tableName( $table );
1399 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1400 $n = mysql_num_fields( $res->result );
1401 for( $i = 0; $i < $n; $i++ ) {
1402 $meta = mysql_fetch_field( $res->result, $i );
1403 if( $field == $meta->name ) {
1404 return new MySQLField($meta);
1407 return false;
1411 * mysql_field_type() wrapper
1413 function fieldType( $res, $index ) {
1414 if ( $res instanceof ResultWrapper ) {
1415 $res = $res->result;
1417 return mysql_field_type( $res, $index );
1421 * Determines if a given index is unique
1423 function indexUnique( $table, $index ) {
1424 $indexInfo = $this->indexInfo( $table, $index );
1425 if ( !$indexInfo ) {
1426 return NULL;
1428 return !$indexInfo[0]->Non_unique;
1432 * INSERT wrapper, inserts an array into a table
1434 * $a may be a single associative array, or an array of these with numeric keys, for
1435 * multi-row insert.
1437 * Usually aborts on failure
1438 * If errors are explicitly ignored, returns success
1440 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1441 # No rows to insert, easy just return now
1442 if ( !count( $a ) ) {
1443 return true;
1446 $table = $this->tableName( $table );
1447 if ( !is_array( $options ) ) {
1448 $options = array( $options );
1450 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1451 $multi = true;
1452 $keys = array_keys( $a[0] );
1453 } else {
1454 $multi = false;
1455 $keys = array_keys( $a );
1458 $sql = 'INSERT ' . implode( ' ', $options ) .
1459 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1461 if ( $multi ) {
1462 $first = true;
1463 foreach ( $a as $row ) {
1464 if ( $first ) {
1465 $first = false;
1466 } else {
1467 $sql .= ',';
1469 $sql .= '(' . $this->makeList( $row ) . ')';
1471 } else {
1472 $sql .= '(' . $this->makeList( $a ) . ')';
1474 return (bool)$this->query( $sql, $fname );
1478 * Make UPDATE options for the Database::update function
1480 * @private
1481 * @param array $options The options passed to Database::update
1482 * @return string
1484 function makeUpdateOptions( $options ) {
1485 if( !is_array( $options ) ) {
1486 $options = array( $options );
1488 $opts = array();
1489 if ( in_array( 'LOW_PRIORITY', $options ) )
1490 $opts[] = $this->lowPriorityOption();
1491 if ( in_array( 'IGNORE', $options ) )
1492 $opts[] = 'IGNORE';
1493 return implode(' ', $opts);
1497 * UPDATE wrapper, takes a condition array and a SET array
1499 * @param string $table The table to UPDATE
1500 * @param array $values An array of values to SET
1501 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1502 * @param string $fname The Class::Function calling this function
1503 * (for the log)
1504 * @param array $options An array of UPDATE options, can be one or
1505 * more of IGNORE, LOW_PRIORITY
1506 * @return bool
1508 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1509 $table = $this->tableName( $table );
1510 $opts = $this->makeUpdateOptions( $options );
1511 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1512 if ( $conds != '*' ) {
1513 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1515 return $this->query( $sql, $fname );
1519 * Makes an encoded list of strings from an array
1520 * $mode:
1521 * LIST_COMMA - comma separated, no field names
1522 * LIST_AND - ANDed WHERE clause (without the WHERE)
1523 * LIST_OR - ORed WHERE clause (without the WHERE)
1524 * LIST_SET - comma separated with field names, like a SET clause
1525 * LIST_NAMES - comma separated field names
1527 function makeList( $a, $mode = LIST_COMMA ) {
1528 if ( !is_array( $a ) ) {
1529 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1532 $first = true;
1533 $list = '';
1534 foreach ( $a as $field => $value ) {
1535 if ( !$first ) {
1536 if ( $mode == LIST_AND ) {
1537 $list .= ' AND ';
1538 } elseif($mode == LIST_OR) {
1539 $list .= ' OR ';
1540 } else {
1541 $list .= ',';
1543 } else {
1544 $first = false;
1546 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1547 $list .= "($value)";
1548 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1549 $list .= "$value";
1550 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1551 $list .= $field." IN (".$this->makeList($value).") ";
1552 } elseif( is_null($value) ) {
1553 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1554 $list .= "$field IS ";
1555 } elseif ( $mode == LIST_SET ) {
1556 $list .= "$field = ";
1558 $list .= 'NULL';
1559 } else {
1560 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1561 $list .= "$field = ";
1563 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1566 return $list;
1570 * Change the current database
1572 function selectDB( $db ) {
1573 $this->mDBname = $db;
1574 return mysql_select_db( $db, $this->mConn );
1578 * Format a table name ready for use in constructing an SQL query
1580 * This does two important things: it quotes table names which as necessary,
1581 * and it adds a table prefix if there is one.
1583 * All functions of this object which require a table name call this function
1584 * themselves. Pass the canonical name to such functions. This is only needed
1585 * when calling query() directly.
1587 * @param string $name database table name
1589 function tableName( $name ) {
1590 global $wgSharedDB;
1591 # Skip quoted literals
1592 if ( $name{0} != '`' ) {
1593 if ( $this->mTablePrefix !== '' && strpos( $name, '.' ) === false ) {
1594 $name = "{$this->mTablePrefix}$name";
1596 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1597 $name = "`$wgSharedDB`.`$name`";
1598 } else {
1599 # Standard quoting
1600 $name = "`$name`";
1603 return $name;
1607 * Fetch a number of table names into an array
1608 * This is handy when you need to construct SQL for joins
1610 * Example:
1611 * extract($dbr->tableNames('user','watchlist'));
1612 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1613 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1615 public function tableNames() {
1616 $inArray = func_get_args();
1617 $retVal = array();
1618 foreach ( $inArray as $name ) {
1619 $retVal[$name] = $this->tableName( $name );
1621 return $retVal;
1625 * Fetch a number of table names into an zero-indexed numerical array
1626 * This is handy when you need to construct SQL for joins
1628 * Example:
1629 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1630 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1631 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1633 public function tableNamesN() {
1634 $inArray = func_get_args();
1635 $retVal = array();
1636 foreach ( $inArray as $name ) {
1637 $retVal[] = $this->tableName( $name );
1639 return $retVal;
1643 * @private
1645 function tableNamesWithUseIndex( $tables, $use_index ) {
1646 $ret = array();
1648 foreach ( $tables as $table )
1649 if ( @$use_index[$table] !== null )
1650 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1651 else
1652 $ret[] = $this->tableName( $table );
1654 return implode( ',', $ret );
1658 * Wrapper for addslashes()
1659 * @param string $s String to be slashed.
1660 * @return string slashed string.
1662 function strencode( $s ) {
1663 return mysql_real_escape_string( $s, $this->mConn );
1667 * If it's a string, adds quotes and backslashes
1668 * Otherwise returns as-is
1670 function addQuotes( $s ) {
1671 if ( is_null( $s ) ) {
1672 return 'NULL';
1673 } else {
1674 # This will also quote numeric values. This should be harmless,
1675 # and protects against weird problems that occur when they really
1676 # _are_ strings such as article titles and string->number->string
1677 # conversion is not 1:1.
1678 return "'" . $this->strencode( $s ) . "'";
1683 * Escape string for safe LIKE usage
1685 function escapeLike( $s ) {
1686 $s=$this->strencode( $s );
1687 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1688 return $s;
1692 * Returns an appropriately quoted sequence value for inserting a new row.
1693 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1694 * subclass will return an integer, and save the value for insertId()
1696 function nextSequenceValue( $seqName ) {
1697 return NULL;
1701 * USE INDEX clause
1702 * PostgreSQL doesn't have them and returns ""
1704 function useIndexClause( $index ) {
1705 return "FORCE INDEX ($index)";
1709 * REPLACE query wrapper
1710 * PostgreSQL simulates this with a DELETE followed by INSERT
1711 * $row is the row to insert, an associative array
1712 * $uniqueIndexes is an array of indexes. Each element may be either a
1713 * field name or an array of field names
1715 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1716 * However if you do this, you run the risk of encountering errors which wouldn't have
1717 * occurred in MySQL
1719 * @todo migrate comment to phodocumentor format
1721 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1722 $table = $this->tableName( $table );
1724 # Single row case
1725 if ( !is_array( reset( $rows ) ) ) {
1726 $rows = array( $rows );
1729 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1730 $first = true;
1731 foreach ( $rows as $row ) {
1732 if ( $first ) {
1733 $first = false;
1734 } else {
1735 $sql .= ',';
1737 $sql .= '(' . $this->makeList( $row ) . ')';
1739 return $this->query( $sql, $fname );
1743 * DELETE where the condition is a join
1744 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1746 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1747 * join condition matches, set $conds='*'
1749 * DO NOT put the join condition in $conds
1751 * @param string $delTable The table to delete from.
1752 * @param string $joinTable The other table.
1753 * @param string $delVar The variable to join on, in the first table.
1754 * @param string $joinVar The variable to join on, in the second table.
1755 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1757 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1758 if ( !$conds ) {
1759 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1762 $delTable = $this->tableName( $delTable );
1763 $joinTable = $this->tableName( $joinTable );
1764 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1765 if ( $conds != '*' ) {
1766 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1769 return $this->query( $sql, $fname );
1773 * Returns the size of a text field, or -1 for "unlimited"
1775 function textFieldSize( $table, $field ) {
1776 $table = $this->tableName( $table );
1777 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1778 $res = $this->query( $sql, 'Database::textFieldSize' );
1779 $row = $this->fetchObject( $res );
1780 $this->freeResult( $res );
1782 $m = array();
1783 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1784 $size = $m[1];
1785 } else {
1786 $size = -1;
1788 return $size;
1792 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1794 function lowPriorityOption() {
1795 return 'LOW_PRIORITY';
1799 * DELETE query wrapper
1801 * Use $conds == "*" to delete all rows
1803 function delete( $table, $conds, $fname = 'Database::delete' ) {
1804 if ( !$conds ) {
1805 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1807 $table = $this->tableName( $table );
1808 $sql = "DELETE FROM $table";
1809 if ( $conds != '*' ) {
1810 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1812 return $this->query( $sql, $fname );
1816 * INSERT SELECT wrapper
1817 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1818 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1819 * $conds may be "*" to copy the whole table
1820 * srcTable may be an array of tables.
1822 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1823 $insertOptions = array(), $selectOptions = array() )
1825 $destTable = $this->tableName( $destTable );
1826 if ( is_array( $insertOptions ) ) {
1827 $insertOptions = implode( ' ', $insertOptions );
1829 if( !is_array( $selectOptions ) ) {
1830 $selectOptions = array( $selectOptions );
1832 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1833 if( is_array( $srcTable ) ) {
1834 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1835 } else {
1836 $srcTable = $this->tableName( $srcTable );
1838 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1839 " SELECT $startOpts " . implode( ',', $varMap ) .
1840 " FROM $srcTable $useIndex ";
1841 if ( $conds != '*' ) {
1842 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1844 $sql .= " $tailOpts";
1845 return $this->query( $sql, $fname );
1849 * Construct a LIMIT query with optional offset
1850 * This is used for query pages
1851 * $sql string SQL query we will append the limit too
1852 * $limit integer the SQL limit
1853 * $offset integer the SQL offset (default false)
1855 function limitResult($sql, $limit, $offset=false) {
1856 if( !is_numeric($limit) ) {
1857 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1859 return " $sql LIMIT "
1860 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1861 . "{$limit} ";
1863 function limitResultForUpdate($sql, $num) {
1864 return $this->limitResult($sql, $num, 0);
1868 * Returns an SQL expression for a simple conditional.
1869 * Uses IF on MySQL.
1871 * @param string $cond SQL expression which will result in a boolean value
1872 * @param string $trueVal SQL expression to return if true
1873 * @param string $falseVal SQL expression to return if false
1874 * @return string SQL fragment
1876 function conditional( $cond, $trueVal, $falseVal ) {
1877 return " IF($cond, $trueVal, $falseVal) ";
1881 * Determines if the last failure was due to a deadlock
1883 function wasDeadlock() {
1884 return $this->lastErrno() == 1213;
1888 * Perform a deadlock-prone transaction.
1890 * This function invokes a callback function to perform a set of write
1891 * queries. If a deadlock occurs during the processing, the transaction
1892 * will be rolled back and the callback function will be called again.
1894 * Usage:
1895 * $dbw->deadlockLoop( callback, ... );
1897 * Extra arguments are passed through to the specified callback function.
1899 * Returns whatever the callback function returned on its successful,
1900 * iteration, or false on error, for example if the retry limit was
1901 * reached.
1903 function deadlockLoop() {
1904 $myFname = 'Database::deadlockLoop';
1906 $this->begin();
1907 $args = func_get_args();
1908 $function = array_shift( $args );
1909 $oldIgnore = $this->ignoreErrors( true );
1910 $tries = DEADLOCK_TRIES;
1911 if ( is_array( $function ) ) {
1912 $fname = $function[0];
1913 } else {
1914 $fname = $function;
1916 do {
1917 $retVal = call_user_func_array( $function, $args );
1918 $error = $this->lastError();
1919 $errno = $this->lastErrno();
1920 $sql = $this->lastQuery();
1922 if ( $errno ) {
1923 if ( $this->wasDeadlock() ) {
1924 # Retry
1925 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1926 } else {
1927 $this->reportQueryError( $error, $errno, $sql, $fname );
1930 } while( $this->wasDeadlock() && --$tries > 0 );
1931 $this->ignoreErrors( $oldIgnore );
1932 if ( $tries <= 0 ) {
1933 $this->query( 'ROLLBACK', $myFname );
1934 $this->reportQueryError( $error, $errno, $sql, $fname );
1935 return false;
1936 } else {
1937 $this->query( 'COMMIT', $myFname );
1938 return $retVal;
1943 * Do a SELECT MASTER_POS_WAIT()
1945 * @param string $file the binlog file
1946 * @param string $pos the binlog position
1947 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1949 function masterPosWait( $file, $pos, $timeout ) {
1950 $fname = 'Database::masterPosWait';
1951 wfProfileIn( $fname );
1954 # Commit any open transactions
1955 $this->immediateCommit();
1957 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1958 $encFile = $this->strencode( $file );
1959 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1960 $res = $this->doQuery( $sql );
1961 if ( $res && $row = $this->fetchRow( $res ) ) {
1962 $this->freeResult( $res );
1963 wfProfileOut( $fname );
1964 return $row[0];
1965 } else {
1966 wfProfileOut( $fname );
1967 return false;
1972 * Get the position of the master from SHOW SLAVE STATUS
1974 function getSlavePos() {
1975 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1976 $row = $this->fetchObject( $res );
1977 if ( $row ) {
1978 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1979 } else {
1980 return array( false, false );
1985 * Get the position of the master from SHOW MASTER STATUS
1987 function getMasterPos() {
1988 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1989 $row = $this->fetchObject( $res );
1990 if ( $row ) {
1991 return array( $row->File, $row->Position );
1992 } else {
1993 return array( false, false );
1998 * Begin a transaction, committing any previously open transaction
2000 function begin( $fname = 'Database::begin' ) {
2001 $this->query( 'BEGIN', $fname );
2002 $this->mTrxLevel = 1;
2006 * End a transaction
2008 function commit( $fname = 'Database::commit' ) {
2009 $this->query( 'COMMIT', $fname );
2010 $this->mTrxLevel = 0;
2014 * Rollback a transaction
2016 function rollback( $fname = 'Database::rollback' ) {
2017 $this->query( 'ROLLBACK', $fname );
2018 $this->mTrxLevel = 0;
2022 * Begin a transaction, committing any previously open transaction
2023 * @deprecated use begin()
2025 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2026 $this->begin();
2030 * Commit transaction, if one is open
2031 * @deprecated use commit()
2033 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2034 $this->commit();
2038 * Return MW-style timestamp used for MySQL schema
2040 function timestamp( $ts=0 ) {
2041 return wfTimestamp(TS_MW,$ts);
2045 * Local database timestamp format or null
2047 function timestampOrNull( $ts = null ) {
2048 if( is_null( $ts ) ) {
2049 return null;
2050 } else {
2051 return $this->timestamp( $ts );
2056 * @todo document
2058 function resultObject( $result ) {
2059 if( empty( $result ) ) {
2060 return false;
2061 } elseif ( $result instanceof ResultWrapper ) {
2062 return $result;
2063 } elseif ( $result === true ) {
2064 // Successful write query
2065 return $result;
2066 } else {
2067 return new ResultWrapper( $this, $result );
2072 * Return aggregated value alias
2074 function aggregateValue ($valuedata,$valuename='value') {
2075 return $valuename;
2079 * @return string wikitext of a link to the server software's web site
2081 function getSoftwareLink() {
2082 return "[http://www.mysql.com/ MySQL]";
2086 * @return string Version information from the database
2088 function getServerVersion() {
2089 return mysql_get_server_info( $this->mConn );
2093 * Ping the server and try to reconnect if it there is no connection
2095 function ping() {
2096 if( function_exists( 'mysql_ping' ) ) {
2097 return mysql_ping( $this->mConn );
2098 } else {
2099 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2100 return true;
2105 * Get slave lag.
2106 * At the moment, this will only work if the DB user has the PROCESS privilege
2108 function getLag() {
2109 $res = $this->query( 'SHOW PROCESSLIST' );
2110 # Find slave SQL thread
2111 while ( $row = $this->fetchObject( $res ) ) {
2112 /* This should work for most situations - when default db
2113 * for thread is not specified, it had no events executed,
2114 * and therefore it doesn't know yet how lagged it is.
2116 * Relay log I/O thread does not select databases.
2118 if ( $row->User == 'system user' &&
2119 $row->State != 'Waiting for master to send event' &&
2120 $row->State != 'Connecting to master' &&
2121 $row->State != 'Queueing master event to the relay log' &&
2122 $row->State != 'Waiting for master update' &&
2123 $row->State != 'Requesting binlog dump'
2125 # This is it, return the time (except -ve)
2126 if ( $row->Time > 0x7fffffff ) {
2127 return false;
2128 } else {
2129 return $row->Time;
2133 return false;
2137 * Get status information from SHOW STATUS in an associative array
2139 function getStatus($which="%") {
2140 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2141 $status = array();
2142 while ( $row = $this->fetchObject( $res ) ) {
2143 $status[$row->Variable_name] = $row->Value;
2145 return $status;
2149 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2151 function maxListLen() {
2152 return 0;
2155 function encodeBlob($b) {
2156 return $b;
2159 function decodeBlob($b) {
2160 return $b;
2164 * Override database's default connection timeout.
2165 * May be useful for very long batch queries such as
2166 * full-wiki dumps, where a single query reads out
2167 * over hours or days.
2168 * @param int $timeout in seconds
2170 public function setTimeout( $timeout ) {
2171 $this->query( "SET net_read_timeout=$timeout" );
2172 $this->query( "SET net_write_timeout=$timeout" );
2176 * Read and execute SQL commands from a file.
2177 * Returns true on success, error string on failure
2178 * @param string $filename File name to open
2179 * @param callback $lineCallback Optional function called before reading each line
2180 * @param callback $resultCallback Optional function called for each MySQL result
2182 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2183 $fp = fopen( $filename, 'r' );
2184 if ( false === $fp ) {
2185 return "Could not open \"{$filename}\".\n";
2187 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2188 fclose( $fp );
2189 return $error;
2193 * Read and execute commands from an open file handle
2194 * Returns true on success, error string on failure
2195 * @param string $fp File handle
2196 * @param callback $lineCallback Optional function called before reading each line
2197 * @param callback $resultCallback Optional function called for each MySQL result
2199 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2200 $cmd = "";
2201 $done = false;
2202 $dollarquote = false;
2204 while ( ! feof( $fp ) ) {
2205 if ( $lineCallback ) {
2206 call_user_func( $lineCallback );
2208 $line = trim( fgets( $fp, 1024 ) );
2209 $sl = strlen( $line ) - 1;
2211 if ( $sl < 0 ) { continue; }
2212 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2214 ## Allow dollar quoting for function declarations
2215 if (substr($line,0,4) == '$mw$') {
2216 if ($dollarquote) {
2217 $dollarquote = false;
2218 $done = true;
2220 else {
2221 $dollarquote = true;
2224 else if (!$dollarquote) {
2225 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2226 $done = true;
2227 $line = substr( $line, 0, $sl );
2231 if ( '' != $cmd ) { $cmd .= ' '; }
2232 $cmd .= "$line\n";
2234 if ( $done ) {
2235 $cmd = str_replace(';;', ";", $cmd);
2236 $cmd = $this->replaceVars( $cmd );
2237 $res = $this->query( $cmd, __METHOD__, true );
2238 if ( $resultCallback ) {
2239 call_user_func( $resultCallback, $res );
2242 if ( false === $res ) {
2243 $err = $this->lastError();
2244 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2247 $cmd = '';
2248 $done = false;
2251 return true;
2256 * Replace variables in sourced SQL
2258 protected function replaceVars( $ins ) {
2259 $varnames = array(
2260 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2261 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2262 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2265 // Ordinary variables
2266 foreach ( $varnames as $var ) {
2267 if( isset( $GLOBALS[$var] ) ) {
2268 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2269 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2270 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2271 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2275 // Table prefixes
2276 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2277 array( &$this, 'tableNameCallback' ), $ins );
2278 return $ins;
2282 * Table name callback
2283 * @private
2285 protected function tableNameCallback( $matches ) {
2286 return $this->tableName( $matches[1] );
2292 * Database abstraction object for mySQL
2293 * Inherit all methods and properties of Database::Database()
2295 * @addtogroup Database
2296 * @see Database
2298 class DatabaseMysql extends Database {
2299 # Inherit all
2304 * Result wrapper for grabbing data queried by someone else
2305 * @addtogroup Database
2307 class ResultWrapper implements Iterator {
2308 var $db, $result, $pos = 0, $currentRow = null;
2311 * Create a new result object from a result resource and a Database object
2313 function ResultWrapper( $database, $result ) {
2314 $this->db = $database;
2315 if ( $result instanceof ResultWrapper ) {
2316 $this->result = $result->result;
2317 } else {
2318 $this->result = $result;
2323 * Get the number of rows in a result object
2325 function numRows() {
2326 return $this->db->numRows( $this->result );
2330 * Fetch the next row from the given result object, in object form.
2331 * Fields can be retrieved with $row->fieldname, with fields acting like
2332 * member variables.
2334 * @param $res SQL result object as returned from Database::query(), etc.
2335 * @return MySQL row object
2336 * @throws DBUnexpectedError Thrown if the database returns an error
2338 function fetchObject() {
2339 return $this->db->fetchObject( $this->result );
2343 * Fetch the next row from the given result object, in associative array
2344 * form. Fields are retrieved with $row['fieldname'].
2346 * @param $res SQL result object as returned from Database::query(), etc.
2347 * @return MySQL row object
2348 * @throws DBUnexpectedError Thrown if the database returns an error
2350 function fetchRow() {
2351 return $this->db->fetchRow( $this->result );
2355 * Free a result object
2357 function free() {
2358 $this->db->freeResult( $this->result );
2359 unset( $this->result );
2360 unset( $this->db );
2364 * Change the position of the cursor in a result object
2365 * See mysql_data_seek()
2367 function seek( $row ) {
2368 $this->db->dataSeek( $this->result, $row );
2371 /*********************
2372 * Iterator functions
2373 * Note that using these in combination with the non-iterator functions
2374 * above may cause rows to be skipped or repeated.
2377 function rewind() {
2378 if ($this->numRows()) {
2379 $this->db->dataSeek($this->result, 0);
2381 $this->pos = 0;
2382 $this->currentRow = null;
2385 function current() {
2386 if ( is_null( $this->currentRow ) ) {
2387 $this->next();
2389 return $this->currentRow;
2392 function key() {
2393 return $this->pos;
2396 function next() {
2397 $this->pos++;
2398 $this->currentRow = $this->fetchObject();
2399 return $this->currentRow;
2402 function valid() {
2403 return $this->current() !== false;