Revert to r15092; massive breakage, unable to connect to MySQL at all
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18 define( 'LIST_OR', 4);
19
20 /** Number of times to re-try an operation in case of deadlock */
21 define( 'DEADLOCK_TRIES', 4 );
22 /** Minimum time to wait before retry, in microseconds */
23 define( 'DEADLOCK_DELAY_MIN', 500000 );
24 /** Maximum time to wait before retry */
25 define( 'DEADLOCK_DELAY_MAX', 1500000 );
26
27 /******************************************************************************
28 * Utility classes
29 *****************************************************************************/
30
31 class DBObject {
32 public $mData;
33
34 function DBObject($data) {
35 $this->mData = $data;
36 }
37
38 function isLOB() {
39 return false;
40 }
41
42 function data() {
43 return $this->mData;
44 }
45 };
46
47 /******************************************************************************
48 * Error classes
49 *****************************************************************************/
50
51 /**
52 * Database error base class
53 */
54 class DBError extends MWException {
55 public $db;
56
57 /**
58 * Construct a database error
59 * @param Database $db The database object which threw the error
60 * @param string $error A simple error message to be used for debugging
61 */
62 function __construct( Database &$db, $error ) {
63 $this->db =& $db;
64 parent::__construct( $error );
65 }
66 }
67
68 class DBConnectionError extends DBError {
69 public $error;
70
71 function __construct( Database &$db, $error = 'unknown error' ) {
72 $msg = 'DB connection error';
73 if ( trim( $error ) != '' ) {
74 $msg .= ": $error";
75 }
76 $this->error = $error;
77 parent::__construct( $db, $msg );
78 }
79
80 function useOutputPage() {
81 // Not likely to work
82 return false;
83 }
84
85 function useMessageCache() {
86 // Not likely to work
87 return false;
88 }
89
90 function getText() {
91 return $this->getMessage() . "\n";
92 }
93
94 function getPageTitle() {
95 global $wgSitename;
96 return "$wgSitename has a problem";
97 }
98
99 function getHTML() {
100 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
101 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
102
103 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
104 # Hard coding strings instead.
105
106 $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>";
107 $mainpage = 'Main Page';
108 $searchdisabled = <<<EOT
109 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
110 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
111 EOT;
112
113 $googlesearch = "
114 <!-- SiteSearch Google -->
115 <FORM method=GET action=\"http://www.google.com/search\">
116 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
117 <A HREF=\"http://www.google.com/\">
118 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
119 border=\"0\" ALT=\"Google\"></A>
120 </td>
121 <td>
122 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
123 <INPUT type=submit name=btnG VALUE=\"Google Search\">
124 <font size=-1>
125 <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 />
126 <input type='hidden' name='ie' value='$2'>
127 <input type='hidden' name='oe' value='$2'>
128 </font>
129 </td></tr></TABLE>
130 </FORM>
131 <!-- SiteSearch Google -->";
132 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
133
134 # No database access
135 if ( is_object( $wgMessageCache ) ) {
136 $wgMessageCache->disable();
137 }
138
139 if ( trim( $this->error ) == '' ) {
140 $this->error = $this->db->getProperty('mServer');
141 }
142
143 $text = str_replace( '$1', $this->error, $noconnect );
144 $text .= wfGetSiteNotice();
145
146 if($wgUseFileCache) {
147 if($wgTitle) {
148 $t =& $wgTitle;
149 } else {
150 if($title) {
151 $t = Title::newFromURL( $title );
152 } elseif (@/**/$_REQUEST['search']) {
153 $search = $_REQUEST['search'];
154 return $searchdisabled .
155 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
156 $wgInputEncoding ), $googlesearch );
157 } else {
158 $t = Title::newFromText( $mainpage );
159 }
160 }
161
162 $cache = new CacheManager( $t );
163 if( $cache->isFileCached() ) {
164 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
165 $cachederror . "</b></p>\n";
166
167 $tag = '<div id="article">';
168 $text = str_replace(
169 $tag,
170 $tag . $msg,
171 $cache->fetchPageText() );
172 }
173 }
174
175 return $text;
176 }
177 }
178
179 class DBQueryError extends DBError {
180 public $error, $errno, $sql, $fname;
181
182 function __construct( Database &$db, $error, $errno, $sql, $fname ) {
183 $message = "A database error has occurred\n" .
184 "Query: $sql\n" .
185 "Function: $fname\n" .
186 "Error: $errno $error\n";
187
188 parent::__construct( $db, $message );
189 $this->error = $error;
190 $this->errno = $errno;
191 $this->sql = $sql;
192 $this->fname = $fname;
193 }
194
195 function getText() {
196 if ( $this->useMessageCache() ) {
197 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
198 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
199 } else {
200 return $this->getMessage();
201 }
202 }
203
204 function getSQL() {
205 global $wgShowSQLErrors;
206 if( !$wgShowSQLErrors ) {
207 return $this->msg( 'sqlhidden', 'SQL hidden' );
208 } else {
209 return $this->sql;
210 }
211 }
212
213 function getPageTitle() {
214 return $this->msg( 'databaseerror', 'Database error' );
215 }
216
217 function getHTML() {
218 if ( $this->useMessageCache() ) {
219 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
220 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
221 } else {
222 return nl2br( htmlspecialchars( $this->getMessage() ) );
223 }
224 }
225 }
226
227 class DBUnexpectedError extends DBError {}
228
229 /******************************************************************************/
230
231 /**
232 * Database abstraction object
233 * @package MediaWiki
234 */
235 class Database {
236
237 #------------------------------------------------------------------------------
238 # Variables
239 #------------------------------------------------------------------------------
240
241 protected $mLastQuery = '';
242
243 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
244 protected $mOut, $mOpened = false;
245
246 protected $mFailFunction;
247 protected $mTablePrefix;
248 protected $mFlags;
249 protected $mTrxLevel = 0;
250 protected $mErrorCount = 0;
251 protected $mLBInfo = array();
252
253 #------------------------------------------------------------------------------
254 # Accessors
255 #------------------------------------------------------------------------------
256 # These optionally set a variable and return the previous state
257
258 /**
259 * Fail function, takes a Database as a parameter
260 * Set to false for default, 1 for ignore errors
261 */
262 function failFunction( $function = NULL ) {
263 return wfSetVar( $this->mFailFunction, $function );
264 }
265
266 /**
267 * Output page, used for reporting errors
268 * FALSE means discard output
269 */
270 function &setOutputPage( &$out ) {
271 $this->mOut =& $out;
272 }
273
274 /**
275 * Boolean, controls output of large amounts of debug information
276 */
277 function debug( $debug = NULL ) {
278 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
279 }
280
281 /**
282 * Turns buffering of SQL result sets on (true) or off (false).
283 * Default is "on" and it should not be changed without good reasons.
284 */
285 function bufferResults( $buffer = NULL ) {
286 if ( is_null( $buffer ) ) {
287 return !(bool)( $this->mFlags & DBO_NOBUFFER );
288 } else {
289 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
290 }
291 }
292
293 /**
294 * Turns on (false) or off (true) the automatic generation and sending
295 * of a "we're sorry, but there has been a database error" page on
296 * database errors. Default is on (false). When turned off, the
297 * code should use wfLastErrno() and wfLastError() to handle the
298 * situation as appropriate.
299 */
300 function ignoreErrors( $ignoreErrors = NULL ) {
301 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
302 }
303
304 /**
305 * The current depth of nested transactions
306 * @param $level Integer: , default NULL.
307 */
308 function trxLevel( $level = NULL ) {
309 return wfSetVar( $this->mTrxLevel, $level );
310 }
311
312 /**
313 * Number of errors logged, only useful when errors are ignored
314 */
315 function errorCount( $count = NULL ) {
316 return wfSetVar( $this->mErrorCount, $count );
317 }
318
319 /**
320 * Properties passed down from the server info array of the load balancer
321 */
322 function getLBInfo( $name = NULL ) {
323 if ( is_null( $name ) ) {
324 return $this->mLBInfo;
325 } else {
326 if ( array_key_exists( $name, $this->mLBInfo ) ) {
327 return $this->mLBInfo[$name];
328 } else {
329 return NULL;
330 }
331 }
332 }
333
334 function setLBInfo( $name, $value = NULL ) {
335 if ( is_null( $value ) ) {
336 $this->mLBInfo = $name;
337 } else {
338 $this->mLBInfo[$name] = $value;
339 }
340 }
341
342 /**#@+
343 * Get function
344 */
345 function lastQuery() { return $this->mLastQuery; }
346 function isOpen() { return $this->mOpened; }
347 /**#@-*/
348
349 function setFlag( $flag ) {
350 $this->mFlags |= $flag;
351 }
352
353 function clearFlag( $flag ) {
354 $this->mFlags &= ~$flag;
355 }
356
357 function getFlag( $flag ) {
358 return !!($this->mFlags & $flag);
359 }
360
361 /**
362 * General read-only accessor
363 */
364 function getProperty( $name ) {
365 return $this->$name;
366 }
367
368 #------------------------------------------------------------------------------
369 # Other functions
370 #------------------------------------------------------------------------------
371
372 /**@{{
373 * @param string $server database server host
374 * @param string $user database user name
375 * @param string $password database user password
376 * @param string $dbname database name
377 */
378
379 /**
380 * @param failFunction
381 * @param $flags
382 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
383 */
384 function __construct( $server = false, $user = false, $password = false, $dbName = false,
385 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
386
387 global $wgOut, $wgDBprefix, $wgCommandLineMode;
388 # Can't get a reference if it hasn't been set yet
389 if ( !isset( $wgOut ) ) {
390 $wgOut = NULL;
391 }
392 $this->mOut =& $wgOut;
393
394 $this->mFailFunction = $failFunction;
395 $this->mFlags = $flags;
396
397 if ( $this->mFlags & DBO_DEFAULT ) {
398 if ( $wgCommandLineMode ) {
399 $this->mFlags &= ~DBO_TRX;
400 } else {
401 $this->mFlags |= DBO_TRX;
402 }
403 }
404
405 /*
406 // Faster read-only access
407 if ( wfReadOnly() ) {
408 $this->mFlags |= DBO_PERSISTENT;
409 $this->mFlags &= ~DBO_TRX;
410 }*/
411
412 /** Get the default table prefix*/
413 if ( $tablePrefix == 'get from global' ) {
414 $this->mTablePrefix = $wgDBprefix;
415 } else {
416 $this->mTablePrefix = $tablePrefix;
417 }
418
419 if ( $server ) {
420 $this->open( $server, $user, $password, $dbName );
421 }
422 }
423
424 /**
425 * @static
426 * @param failFunction
427 * @param $flags
428 */
429 static function newFromParams( $server, $user, $password, $dbName,
430 $failFunction = false, $flags = 0 )
431 {
432 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
433 }
434
435 /**
436 * Usually aborts on failure
437 * If the failFunction is set to a non-zero integer, returns success
438 */
439 function open( $server, $user, $password, $dbName ) {
440 global $wguname;
441
442 # Test for missing mysql.so
443 # First try to load it
444 if (!@extension_loaded('mysql')) {
445 @dl('mysql.so');
446 }
447
448 # Fail now
449 # Otherwise we get a suppressed fatal error, which is very hard to track down
450 if ( !function_exists( 'mysql_connect' ) ) {
451 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
452 }
453
454 $this->close();
455 $this->mServer = $server;
456 $this->mUser = $user;
457 $this->mPassword = $password;
458 $this->mDBname = $dbName;
459
460 $success = false;
461
462 if ( $this->mFlags & DBO_PERSISTENT ) {
463 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
464 } else {
465 # Create a new connection...
466 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
467 }
468
469 if ( $dbName != '' ) {
470 if ( $this->mConn !== false ) {
471 $success = @/**/mysql_select_db( $dbName, $this->mConn );
472 if ( !$success ) {
473 $error = "Error selecting database $dbName on server {$this->mServer} " .
474 "from client host {$wguname['nodename']}\n";
475 wfDebug( $error );
476 }
477 } else {
478 wfDebug( "DB connection error\n" );
479 wfDebug( "Server: $server, User: $user, Password: " .
480 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
481 $success = false;
482 }
483 } else {
484 # Delay USE query
485 $success = (bool)$this->mConn;
486 }
487
488 if ( !$success ) {
489 $this->reportConnectionError();
490 }
491
492 global $wgDBmysql5;
493 if( $wgDBmysql5 ) {
494 // Tell the server we're communicating with it in UTF-8.
495 // This may engage various charset conversions.
496 $this->query( 'SET NAMES utf8' );
497 }
498
499 $this->mOpened = $success;
500 return $success;
501 }
502 /**@}}*/
503
504 /**
505 * Closes a database connection.
506 * if it is open : commits any open transactions
507 *
508 * @return bool operation success. true if already closed.
509 */
510 function close()
511 {
512 $this->mOpened = false;
513 if ( $this->mConn ) {
514 if ( $this->trxLevel() ) {
515 $this->immediateCommit();
516 }
517 return mysql_close( $this->mConn );
518 } else {
519 return true;
520 }
521 }
522
523 /**
524 * @param string $error fallback error message, used if none is given by MySQL
525 */
526 function reportConnectionError( $error = 'Unknown error' ) {
527 $myError = $this->lastError();
528 if ( $myError ) {
529 $error = $myError;
530 }
531
532 if ( $this->mFailFunction ) {
533 # Legacy error handling method
534 if ( !is_int( $this->mFailFunction ) ) {
535 $ff = $this->mFailFunction;
536 $ff( $this, $error );
537 }
538 } else {
539 # New method
540 wfLogDBError( "Connection error: $error\n" );
541 throw new DBConnectionError( $this, $error );
542 }
543 }
544
545 /**
546 * Usually aborts on failure
547 * If errors are explicitly ignored, returns success
548 */
549 function query( $sql, $fname = '', $tempIgnore = false ) {
550 global $wgProfiling;
551
552 if ( $wgProfiling ) {
553 # generalizeSQL will probably cut down the query to reasonable
554 # logging size most of the time. The substr is really just a sanity check.
555
556 # Who's been wasting my precious column space? -- TS
557 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
558
559 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
560 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
561 $totalProf = 'Database::query';
562 } else {
563 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
564 $totalProf = 'Database::query-master';
565 }
566 wfProfileIn( $totalProf );
567 wfProfileIn( $queryProf );
568 }
569
570 $this->mLastQuery = $sql;
571
572 # Add a comment for easy SHOW PROCESSLIST interpretation
573 if ( $fname ) {
574 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
575 } else {
576 $commentedSql = $sql;
577 }
578
579 # If DBO_TRX is set, start a transaction
580 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
581 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
582 ) {
583 $this->begin();
584 }
585
586 if ( $this->debug() ) {
587 $sqlx = substr( $commentedSql, 0, 500 );
588 $sqlx = strtr( $sqlx, "\t\n", ' ' );
589 wfDebug( "SQL: $sqlx\n" );
590 }
591
592 # Do the query and handle errors
593 $ret = $this->doQuery( $commentedSql );
594
595 # Try reconnecting if the connection was lost
596 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
597 # Transaction is gone, like it or not
598 $this->mTrxLevel = 0;
599 wfDebug( "Connection lost, reconnecting...\n" );
600 if ( $this->ping() ) {
601 wfDebug( "Reconnected\n" );
602 $ret = $this->doQuery( $commentedSql );
603 } else {
604 wfDebug( "Failed\n" );
605 }
606 }
607
608 if ( false === $ret ) {
609 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
610 }
611
612 if ( $wgProfiling ) {
613 wfProfileOut( $queryProf );
614 wfProfileOut( $totalProf );
615 }
616 return $ret;
617 }
618
619 /**
620 * The DBMS-dependent part of query()
621 * @param string $sql SQL query.
622 */
623 function doQuery( $sql ) {
624 if( $this->bufferResults() ) {
625 $ret = mysql_query( $sql, $this->mConn );
626 } else {
627 $ret = mysql_unbuffered_query( $sql, $this->mConn );
628 }
629 return $ret;
630 }
631
632 /**
633 * @param $error
634 * @param $errno
635 * @param $sql
636 * @param string $fname
637 * @param bool $tempIgnore
638 */
639 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
640 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
641 # Ignore errors during error handling to avoid infinite recursion
642 $ignore = $this->ignoreErrors( true );
643 ++$this->mErrorCount;
644
645 if( $ignore || $tempIgnore ) {
646 wfDebug("SQL ERROR (ignored): $error\n");
647 $this->ignoreErrors( $ignore );
648 } else {
649 $sql1line = str_replace( "\n", "\\n", $sql );
650 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
651 wfDebug("SQL ERROR: " . $error . "\n");
652 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
653 }
654 }
655
656
657 /**
658 * Intended to be compatible with the PEAR::DB wrapper functions.
659 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
660 *
661 * ? = scalar value, quoted as necessary
662 * ! = raw SQL bit (a function for instance)
663 * & = filename; reads the file and inserts as a blob
664 * (we don't use this though...)
665 */
666 function prepare( $sql, $func = 'Database::prepare' ) {
667 /* MySQL doesn't support prepared statements (yet), so just
668 pack up the query for reference. We'll manually replace
669 the bits later. */
670 return array( 'query' => $sql, 'func' => $func );
671 }
672
673 function freePrepared( $prepared ) {
674 /* No-op for MySQL */
675 }
676
677 /**
678 * Execute a prepared query with the various arguments
679 * @param string $prepared the prepared sql
680 * @param mixed $args Either an array here, or put scalars as varargs
681 */
682 function execute( $prepared, $args = null ) {
683 if( !is_array( $args ) ) {
684 # Pull the var args
685 $args = func_get_args();
686 array_shift( $args );
687 }
688 $sql = $this->fillPrepared( $prepared['query'], $args );
689 return $this->query( $sql, $prepared['func'] );
690 }
691
692 /**
693 * Prepare & execute an SQL statement, quoting and inserting arguments
694 * in the appropriate places.
695 * @param string $query
696 * @param string $args ...
697 */
698 function safeQuery( $query, $args = null ) {
699 $prepared = $this->prepare( $query, 'Database::safeQuery' );
700 if( !is_array( $args ) ) {
701 # Pull the var args
702 $args = func_get_args();
703 array_shift( $args );
704 }
705 $retval = $this->execute( $prepared, $args );
706 $this->freePrepared( $prepared );
707 return $retval;
708 }
709
710 /**
711 * For faking prepared SQL statements on DBs that don't support
712 * it directly.
713 * @param string $preparedSql - a 'preparable' SQL statement
714 * @param array $args - array of arguments to fill it with
715 * @return string executable SQL
716 */
717 function fillPrepared( $preparedQuery, $args ) {
718 reset( $args );
719 $this->preparedArgs =& $args;
720 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
721 array( &$this, 'fillPreparedArg' ), $preparedQuery );
722 }
723
724 /**
725 * preg_callback func for fillPrepared()
726 * The arguments should be in $this->preparedArgs and must not be touched
727 * while we're doing this.
728 *
729 * @param array $matches
730 * @return string
731 * @private
732 */
733 function fillPreparedArg( $matches ) {
734 switch( $matches[1] ) {
735 case '\\?': return '?';
736 case '\\!': return '!';
737 case '\\&': return '&';
738 }
739 list( $n, $arg ) = each( $this->preparedArgs );
740 switch( $matches[1] ) {
741 case '?': return $this->addQuotes( $arg );
742 case '!': return $arg;
743 case '&':
744 # return $this->addQuotes( file_get_contents( $arg ) );
745 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
746 default:
747 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
748 }
749 }
750
751 /**#@+
752 * @param mixed $res A SQL result
753 */
754 /**
755 * Free a result object
756 */
757 function freeResult( $res ) {
758 if ( !@/**/mysql_free_result( $res ) ) {
759 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
760 }
761 }
762
763 /**
764 * Fetch the next row from the given result object, in object form
765 */
766 function fetchObject( $res ) {
767 @/**/$row = mysql_fetch_object( $res );
768 if( mysql_errno() ) {
769 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
770 }
771 return $row;
772 }
773
774 /**
775 * Fetch the next row from the given result object
776 * Returns an array
777 */
778 function fetchRow( $res ) {
779 @/**/$row = mysql_fetch_array( $res );
780 if (mysql_errno() ) {
781 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
782 }
783 return $row;
784 }
785
786 /**
787 * Get the number of rows in a result object
788 */
789 function numRows( $res ) {
790 @/**/$n = mysql_num_rows( $res );
791 if( mysql_errno() ) {
792 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
793 }
794 return $n;
795 }
796
797 /**
798 * Get the number of fields in a result object
799 * See documentation for mysql_num_fields()
800 */
801 function numFields( $res ) { return mysql_num_fields( $res ); }
802
803 /**
804 * Get a field name in a result object
805 * See documentation for mysql_field_name():
806 * http://www.php.net/mysql_field_name
807 */
808 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
809
810 /**
811 * Get the inserted value of an auto-increment row
812 *
813 * The value inserted should be fetched from nextSequenceValue()
814 *
815 * Example:
816 * $id = $dbw->nextSequenceValue('page_page_id_seq');
817 * $dbw->insert('page',array('page_id' => $id));
818 * $id = $dbw->insertId();
819 */
820 function insertId() { return mysql_insert_id( $this->mConn ); }
821
822 /**
823 * Change the position of the cursor in a result object
824 * See mysql_data_seek()
825 */
826 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
827
828 /**
829 * Get the last error number
830 * See mysql_errno()
831 */
832 function lastErrno() {
833 if ( $this->mConn ) {
834 return mysql_errno( $this->mConn );
835 } else {
836 return mysql_errno();
837 }
838 }
839
840 /**
841 * Get a description of the last error
842 * See mysql_error() for more details
843 */
844 function lastError() {
845 if ( $this->mConn ) {
846 # Even if it's non-zero, it can still be invalid
847 wfSuppressWarnings();
848 $error = mysql_error( $this->mConn );
849 if ( !$error ) {
850 $error = mysql_error();
851 }
852 wfRestoreWarnings();
853 } else {
854 $error = mysql_error();
855 }
856 if( $error ) {
857 $error .= ' (' . $this->mServer . ')';
858 }
859 return $error;
860 }
861 /**
862 * Get the number of rows affected by the last write query
863 * See mysql_affected_rows() for more details
864 */
865 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
866 /**#@-*/ // end of template : @param $result
867
868 /**
869 * Simple UPDATE wrapper
870 * Usually aborts on failure
871 * If errors are explicitly ignored, returns success
872 *
873 * This function exists for historical reasons, Database::update() has a more standard
874 * calling convention and feature set
875 */
876 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
877 {
878 $table = $this->tableName( $table );
879 $sql = "UPDATE $table SET $var = '" .
880 $this->strencode( $value ) . "' WHERE ($cond)";
881 return (bool)$this->query( $sql, $fname );
882 }
883
884 /**
885 * Simple SELECT wrapper, returns a single field, input must be encoded
886 * Usually aborts on failure
887 * If errors are explicitly ignored, returns FALSE on failure
888 */
889 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
890 if ( !is_array( $options ) ) {
891 $options = array( $options );
892 }
893 $options['LIMIT'] = 1;
894
895 $res = $this->select( $table, $var, $cond, $fname, $options );
896 if ( $res === false || !$this->numRows( $res ) ) {
897 return false;
898 }
899 $row = $this->fetchRow( $res );
900 if ( $row !== false ) {
901 $this->freeResult( $res );
902 return $row[0];
903 } else {
904 return false;
905 }
906 }
907
908 /**
909 * Returns an optional USE INDEX clause to go after the table, and a
910 * string to go at the end of the query
911 *
912 * @private
913 *
914 * @param array $options an associative array of options to be turned into
915 * an SQL query, valid keys are listed in the function.
916 * @return array
917 */
918 function makeSelectOptions( $options ) {
919 $tailOpts = '';
920 $startOpts = '';
921
922 $noKeyOptions = array();
923 foreach ( $options as $key => $option ) {
924 if ( is_numeric( $key ) ) {
925 $noKeyOptions[$option] = true;
926 }
927 }
928
929 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
930 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
931
932 if (isset($options['LIMIT'])) {
933 $tailOpts .= $this->limitResult('', $options['LIMIT'],
934 isset($options['OFFSET']) ? $options['OFFSET'] : false);
935 }
936
937 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
938 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
939 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
940
941 # Various MySQL extensions
942 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
943 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
944 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
945 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
946 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
947 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
948 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
949
950 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
951 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
952 } else {
953 $useIndex = '';
954 }
955
956 return array( $startOpts, $useIndex, $tailOpts );
957 }
958
959 /**
960 * SELECT wrapper
961 */
962 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
963 {
964 if( is_array( $vars ) ) {
965 $vars = implode( ',', $vars );
966 }
967 if( !is_array( $options ) ) {
968 $options = array( $options );
969 }
970 if( is_array( $table ) ) {
971 if ( @is_array( $options['USE INDEX'] ) )
972 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
973 else
974 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
975 } elseif ($table!='') {
976 $from = ' FROM ' . $this->tableName( $table );
977 } else {
978 $from = '';
979 }
980
981 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
982
983 if( !empty( $conds ) ) {
984 if ( is_array( $conds ) ) {
985 $conds = $this->makeList( $conds, LIST_AND );
986 }
987 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
988 } else {
989 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
990 }
991
992 return $this->query( $sql, $fname );
993 }
994
995 /**
996 * Single row SELECT wrapper
997 * Aborts or returns FALSE on error
998 *
999 * $vars: the selected variables
1000 * $conds: a condition map, terms are ANDed together.
1001 * Items with numeric keys are taken to be literal conditions
1002 * Takes an array of selected variables, and a condition map, which is ANDed
1003 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1004 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1005 * $obj- >page_id is the ID of the Astronomy article
1006 *
1007 * @todo migrate documentation to phpdocumentor format
1008 */
1009 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1010 $options['LIMIT'] = 1;
1011 $res = $this->select( $table, $vars, $conds, $fname, $options );
1012 if ( $res === false )
1013 return false;
1014 if ( !$this->numRows($res) ) {
1015 $this->freeResult($res);
1016 return false;
1017 }
1018 $obj = $this->fetchObject( $res );
1019 $this->freeResult( $res );
1020 return $obj;
1021
1022 }
1023
1024 /**
1025 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1026 * It's only slightly flawed. Don't use for anything important.
1027 *
1028 * @param string $sql A SQL Query
1029 * @static
1030 */
1031 static function generalizeSQL( $sql ) {
1032 # This does the same as the regexp below would do, but in such a way
1033 # as to avoid crashing php on some large strings.
1034 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1035
1036 $sql = str_replace ( "\\\\", '', $sql);
1037 $sql = str_replace ( "\\'", '', $sql);
1038 $sql = str_replace ( "\\\"", '', $sql);
1039 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1040 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1041
1042 # All newlines, tabs, etc replaced by single space
1043 $sql = preg_replace ( "/\s+/", ' ', $sql);
1044
1045 # All numbers => N
1046 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1047
1048 return $sql;
1049 }
1050
1051 /**
1052 * Determines whether a field exists in a table
1053 * Usually aborts on failure
1054 * If errors are explicitly ignored, returns NULL on failure
1055 */
1056 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1057 $table = $this->tableName( $table );
1058 $res = $this->query( 'DESCRIBE '.$table, $fname );
1059 if ( !$res ) {
1060 return NULL;
1061 }
1062
1063 $found = false;
1064
1065 while ( $row = $this->fetchObject( $res ) ) {
1066 if ( $row->Field == $field ) {
1067 $found = true;
1068 break;
1069 }
1070 }
1071 return $found;
1072 }
1073
1074 /**
1075 * Determines whether an index exists
1076 * Usually aborts on failure
1077 * If errors are explicitly ignored, returns NULL on failure
1078 */
1079 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1080 $info = $this->indexInfo( $table, $index, $fname );
1081 if ( is_null( $info ) ) {
1082 return NULL;
1083 } else {
1084 return $info !== false;
1085 }
1086 }
1087
1088
1089 /**
1090 * Get information about an index into an object
1091 * Returns false if the index does not exist
1092 */
1093 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1094 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1095 # SHOW INDEX should work for 3.x and up:
1096 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1097 $table = $this->tableName( $table );
1098 $sql = 'SHOW INDEX FROM '.$table;
1099 $res = $this->query( $sql, $fname );
1100 if ( !$res ) {
1101 return NULL;
1102 }
1103
1104 while ( $row = $this->fetchObject( $res ) ) {
1105 if ( $row->Key_name == $index ) {
1106 return $row;
1107 }
1108 }
1109 return false;
1110 }
1111
1112 /**
1113 * Query whether a given table exists
1114 */
1115 function tableExists( $table ) {
1116 $table = $this->tableName( $table );
1117 $old = $this->ignoreErrors( true );
1118 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1119 $this->ignoreErrors( $old );
1120 if( $res ) {
1121 $this->freeResult( $res );
1122 return true;
1123 } else {
1124 return false;
1125 }
1126 }
1127
1128 /**
1129 * mysql_fetch_field() wrapper
1130 * Returns false if the field doesn't exist
1131 *
1132 * @param $table
1133 * @param $field
1134 */
1135 function fieldInfo( $table, $field ) {
1136 $table = $this->tableName( $table );
1137 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1138 $n = mysql_num_fields( $res );
1139 for( $i = 0; $i < $n; $i++ ) {
1140 $meta = mysql_fetch_field( $res, $i );
1141 if( $field == $meta->name ) {
1142 return $meta;
1143 }
1144 }
1145 return false;
1146 }
1147
1148 /**
1149 * mysql_field_type() wrapper
1150 */
1151 function fieldType( $res, $index ) {
1152 return mysql_field_type( $res, $index );
1153 }
1154
1155 /**
1156 * Determines if a given index is unique
1157 */
1158 function indexUnique( $table, $index ) {
1159 $indexInfo = $this->indexInfo( $table, $index );
1160 if ( !$indexInfo ) {
1161 return NULL;
1162 }
1163 return !$indexInfo->Non_unique;
1164 }
1165
1166 /**
1167 * INSERT wrapper, inserts an array into a table
1168 *
1169 * $a may be a single associative array, or an array of these with numeric keys, for
1170 * multi-row insert.
1171 *
1172 * Usually aborts on failure
1173 * If errors are explicitly ignored, returns success
1174 */
1175 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1176 # No rows to insert, easy just return now
1177 if ( !count( $a ) ) {
1178 return true;
1179 }
1180
1181 $table = $this->tableName( $table );
1182 if ( !is_array( $options ) ) {
1183 $options = array( $options );
1184 }
1185 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1186 $multi = true;
1187 $keys = array_keys( $a[0] );
1188 } else {
1189 $multi = false;
1190 $keys = array_keys( $a );
1191 }
1192
1193 $sql = 'INSERT ' . implode( ' ', $options ) .
1194 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1195
1196 if ( $multi ) {
1197 $first = true;
1198 foreach ( $a as $row ) {
1199 if ( $first ) {
1200 $first = false;
1201 } else {
1202 $sql .= ',';
1203 }
1204 $sql .= '(' . $this->makeList( $row ) . ')';
1205 }
1206 } else {
1207 $sql .= '(' . $this->makeList( $a ) . ')';
1208 }
1209 return (bool)$this->query( $sql, $fname );
1210 }
1211
1212 /**
1213 * Make UPDATE options for the Database::update function
1214 *
1215 * @private
1216 * @param array $options The options passed to Database::update
1217 * @return string
1218 */
1219 function makeUpdateOptions( $options ) {
1220 if( !is_array( $options ) ) {
1221 $options = array( $options );
1222 }
1223 $opts = array();
1224 if ( in_array( 'LOW_PRIORITY', $options ) )
1225 $opts[] = $this->lowPriorityOption();
1226 if ( in_array( 'IGNORE', $options ) )
1227 $opts[] = 'IGNORE';
1228 return implode(' ', $opts);
1229 }
1230
1231 /**
1232 * UPDATE wrapper, takes a condition array and a SET array
1233 *
1234 * @param string $table The table to UPDATE
1235 * @param array $values An array of values to SET
1236 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1237 * @param string $fname The Class::Function calling this function
1238 * (for the log)
1239 * @param array $options An array of UPDATE options, can be one or
1240 * more of IGNORE, LOW_PRIORITY
1241 */
1242 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1243 $table = $this->tableName( $table );
1244 $opts = $this->makeUpdateOptions( $options );
1245 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1246 if ( $conds != '*' ) {
1247 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1248 }
1249 $this->query( $sql, $fname );
1250 }
1251
1252 /**
1253 * Makes a wfStrencoded list from an array
1254 * $mode:
1255 * LIST_COMMA - comma separated, no field names
1256 * LIST_AND - ANDed WHERE clause (without the WHERE)
1257 * LIST_OR - ORed WHERE clause (without the WHERE)
1258 * LIST_SET - comma separated with field names, like a SET clause
1259 * LIST_NAMES - comma separated field names
1260 */
1261 function makeList( $a, $mode = LIST_COMMA ) {
1262 if ( !is_array( $a ) ) {
1263 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1264 }
1265
1266 $first = true;
1267 $list = '';
1268 foreach ( $a as $field => $value ) {
1269 if ( !$first ) {
1270 if ( $mode == LIST_AND ) {
1271 $list .= ' AND ';
1272 } elseif($mode == LIST_OR) {
1273 $list .= ' OR ';
1274 } else {
1275 $list .= ',';
1276 }
1277 } else {
1278 $first = false;
1279 }
1280 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1281 $list .= "($value)";
1282 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1283 $list .= $field." IN (".$this->makeList($value).") ";
1284 } else {
1285 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1286 $list .= "$field = ";
1287 }
1288 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1289 }
1290 }
1291 return $list;
1292 }
1293
1294 /**
1295 * Change the current database
1296 */
1297 function selectDB( $db ) {
1298 $this->mDBname = $db;
1299 return mysql_select_db( $db, $this->mConn );
1300 }
1301
1302 /**
1303 * Format a table name ready for use in constructing an SQL query
1304 *
1305 * This does two important things: it quotes table names which as necessary,
1306 * and it adds a table prefix if there is one.
1307 *
1308 * All functions of this object which require a table name call this function
1309 * themselves. Pass the canonical name to such functions. This is only needed
1310 * when calling query() directly.
1311 *
1312 * @param string $name database table name
1313 */
1314 function tableName( $name ) {
1315 global $wgSharedDB;
1316 # Skip quoted literals
1317 if ( $name{0} != '`' ) {
1318 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1319 $name = "{$this->mTablePrefix}$name";
1320 }
1321 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1322 $name = "`$wgSharedDB`.`$name`";
1323 } else {
1324 # Standard quoting
1325 $name = "`$name`";
1326 }
1327 }
1328 return $name;
1329 }
1330
1331 /**
1332 * Fetch a number of table names into an array
1333 * This is handy when you need to construct SQL for joins
1334 *
1335 * Example:
1336 * extract($dbr->tableNames('user','watchlist'));
1337 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1338 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1339 */
1340 function tableNames() {
1341 $inArray = func_get_args();
1342 $retVal = array();
1343 foreach ( $inArray as $name ) {
1344 $retVal[$name] = $this->tableName( $name );
1345 }
1346 return $retVal;
1347 }
1348
1349 /**
1350 * @private
1351 */
1352 function tableNamesWithUseIndex( $tables, $use_index ) {
1353 $ret = array();
1354
1355 foreach ( $tables as $table )
1356 if ( @$use_index[$table] !== null )
1357 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1358 else
1359 $ret[] = $this->tableName( $table );
1360
1361 return implode( ',', $ret );
1362 }
1363
1364 /**
1365 * Wrapper for addslashes()
1366 * @param string $s String to be slashed.
1367 * @return string slashed string.
1368 */
1369 function strencode( $s ) {
1370 return addslashes( $s );
1371 }
1372
1373 /**
1374 * If it's a string, adds quotes and backslashes
1375 * Otherwise returns as-is
1376 */
1377 function addQuotes( $s ) {
1378 if ( is_null( $s ) ) {
1379 return 'NULL';
1380 } else {
1381 # This will also quote numeric values. This should be harmless,
1382 # and protects against weird problems that occur when they really
1383 # _are_ strings such as article titles and string->number->string
1384 # conversion is not 1:1.
1385 return "'" . $this->strencode( $s ) . "'";
1386 }
1387 }
1388
1389 /**
1390 * Escape string for safe LIKE usage
1391 */
1392 function escapeLike( $s ) {
1393 $s=$this->strencode( $s );
1394 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1395 return $s;
1396 }
1397
1398 /**
1399 * Returns an appropriately quoted sequence value for inserting a new row.
1400 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1401 * subclass will return an integer, and save the value for insertId()
1402 */
1403 function nextSequenceValue( $seqName ) {
1404 return NULL;
1405 }
1406
1407 /**
1408 * USE INDEX clause
1409 * PostgreSQL doesn't have them and returns ""
1410 */
1411 function useIndexClause( $index ) {
1412 return "FORCE INDEX ($index)";
1413 }
1414
1415 /**
1416 * REPLACE query wrapper
1417 * PostgreSQL simulates this with a DELETE followed by INSERT
1418 * $row is the row to insert, an associative array
1419 * $uniqueIndexes is an array of indexes. Each element may be either a
1420 * field name or an array of field names
1421 *
1422 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1423 * However if you do this, you run the risk of encountering errors which wouldn't have
1424 * occurred in MySQL
1425 *
1426 * @todo migrate comment to phodocumentor format
1427 */
1428 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1429 $table = $this->tableName( $table );
1430
1431 # Single row case
1432 if ( !is_array( reset( $rows ) ) ) {
1433 $rows = array( $rows );
1434 }
1435
1436 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1437 $first = true;
1438 foreach ( $rows as $row ) {
1439 if ( $first ) {
1440 $first = false;
1441 } else {
1442 $sql .= ',';
1443 }
1444 $sql .= '(' . $this->makeList( $row ) . ')';
1445 }
1446 return $this->query( $sql, $fname );
1447 }
1448
1449 /**
1450 * DELETE where the condition is a join
1451 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1452 *
1453 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1454 * join condition matches, set $conds='*'
1455 *
1456 * DO NOT put the join condition in $conds
1457 *
1458 * @param string $delTable The table to delete from.
1459 * @param string $joinTable The other table.
1460 * @param string $delVar The variable to join on, in the first table.
1461 * @param string $joinVar The variable to join on, in the second table.
1462 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1463 */
1464 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1465 if ( !$conds ) {
1466 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1467 }
1468
1469 $delTable = $this->tableName( $delTable );
1470 $joinTable = $this->tableName( $joinTable );
1471 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1472 if ( $conds != '*' ) {
1473 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1474 }
1475
1476 return $this->query( $sql, $fname );
1477 }
1478
1479 /**
1480 * Returns the size of a text field, or -1 for "unlimited"
1481 */
1482 function textFieldSize( $table, $field ) {
1483 $table = $this->tableName( $table );
1484 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1485 $res = $this->query( $sql, 'Database::textFieldSize' );
1486 $row = $this->fetchObject( $res );
1487 $this->freeResult( $res );
1488
1489 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1490 $size = $m[1];
1491 } else {
1492 $size = -1;
1493 }
1494 return $size;
1495 }
1496
1497 /**
1498 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1499 */
1500 function lowPriorityOption() {
1501 return 'LOW_PRIORITY';
1502 }
1503
1504 /**
1505 * DELETE query wrapper
1506 *
1507 * Use $conds == "*" to delete all rows
1508 */
1509 function delete( $table, $conds, $fname = 'Database::delete' ) {
1510 if ( !$conds ) {
1511 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1512 }
1513 $table = $this->tableName( $table );
1514 $sql = "DELETE FROM $table";
1515 if ( $conds != '*' ) {
1516 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1517 }
1518 return $this->query( $sql, $fname );
1519 }
1520
1521 /**
1522 * INSERT SELECT wrapper
1523 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1524 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1525 * $conds may be "*" to copy the whole table
1526 * srcTable may be an array of tables.
1527 */
1528 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1529 $insertOptions = array(), $selectOptions = array() )
1530 {
1531 $destTable = $this->tableName( $destTable );
1532 if ( is_array( $insertOptions ) ) {
1533 $insertOptions = implode( ' ', $insertOptions );
1534 }
1535 if( !is_array( $selectOptions ) ) {
1536 $selectOptions = array( $selectOptions );
1537 }
1538 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1539 if( is_array( $srcTable ) ) {
1540 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1541 } else {
1542 $srcTable = $this->tableName( $srcTable );
1543 }
1544 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1545 " SELECT $startOpts " . implode( ',', $varMap ) .
1546 " FROM $srcTable $useIndex ";
1547 if ( $conds != '*' ) {
1548 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1549 }
1550 $sql .= " $tailOpts";
1551 return $this->query( $sql, $fname );
1552 }
1553
1554 /**
1555 * Construct a LIMIT query with optional offset
1556 * This is used for query pages
1557 * $sql string SQL query we will append the limit too
1558 * $limit integer the SQL limit
1559 * $offset integer the SQL offset (default false)
1560 */
1561 function limitResult($sql, $limit, $offset=false) {
1562 if( !is_numeric($limit) ) {
1563 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1564 }
1565 return " $sql LIMIT "
1566 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1567 . "{$limit} ";
1568 }
1569 function limitResultForUpdate($sql, $num) {
1570 return $this->limitResult($sql, $num, 0);
1571 }
1572
1573 /**
1574 * Returns an SQL expression for a simple conditional.
1575 * Uses IF on MySQL.
1576 *
1577 * @param string $cond SQL expression which will result in a boolean value
1578 * @param string $trueVal SQL expression to return if true
1579 * @param string $falseVal SQL expression to return if false
1580 * @return string SQL fragment
1581 */
1582 function conditional( $cond, $trueVal, $falseVal ) {
1583 return " IF($cond, $trueVal, $falseVal) ";
1584 }
1585
1586 /**
1587 * Determines if the last failure was due to a deadlock
1588 */
1589 function wasDeadlock() {
1590 return $this->lastErrno() == 1213;
1591 }
1592
1593 /**
1594 * Perform a deadlock-prone transaction.
1595 *
1596 * This function invokes a callback function to perform a set of write
1597 * queries. If a deadlock occurs during the processing, the transaction
1598 * will be rolled back and the callback function will be called again.
1599 *
1600 * Usage:
1601 * $dbw->deadlockLoop( callback, ... );
1602 *
1603 * Extra arguments are passed through to the specified callback function.
1604 *
1605 * Returns whatever the callback function returned on its successful,
1606 * iteration, or false on error, for example if the retry limit was
1607 * reached.
1608 */
1609 function deadlockLoop() {
1610 $myFname = 'Database::deadlockLoop';
1611
1612 $this->begin();
1613 $args = func_get_args();
1614 $function = array_shift( $args );
1615 $oldIgnore = $this->ignoreErrors( true );
1616 $tries = DEADLOCK_TRIES;
1617 if ( is_array( $function ) ) {
1618 $fname = $function[0];
1619 } else {
1620 $fname = $function;
1621 }
1622 do {
1623 $retVal = call_user_func_array( $function, $args );
1624 $error = $this->lastError();
1625 $errno = $this->lastErrno();
1626 $sql = $this->lastQuery();
1627
1628 if ( $errno ) {
1629 if ( $this->wasDeadlock() ) {
1630 # Retry
1631 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1632 } else {
1633 $this->reportQueryError( $error, $errno, $sql, $fname );
1634 }
1635 }
1636 } while( $this->wasDeadlock() && --$tries > 0 );
1637 $this->ignoreErrors( $oldIgnore );
1638 if ( $tries <= 0 ) {
1639 $this->query( 'ROLLBACK', $myFname );
1640 $this->reportQueryError( $error, $errno, $sql, $fname );
1641 return false;
1642 } else {
1643 $this->query( 'COMMIT', $myFname );
1644 return $retVal;
1645 }
1646 }
1647
1648 /**
1649 * Do a SELECT MASTER_POS_WAIT()
1650 *
1651 * @param string $file the binlog file
1652 * @param string $pos the binlog position
1653 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1654 */
1655 function masterPosWait( $file, $pos, $timeout ) {
1656 $fname = 'Database::masterPosWait';
1657 wfProfileIn( $fname );
1658
1659
1660 # Commit any open transactions
1661 $this->immediateCommit();
1662
1663 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1664 $encFile = $this->strencode( $file );
1665 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1666 $res = $this->doQuery( $sql );
1667 if ( $res && $row = $this->fetchRow( $res ) ) {
1668 $this->freeResult( $res );
1669 wfProfileOut( $fname );
1670 return $row[0];
1671 } else {
1672 wfProfileOut( $fname );
1673 return false;
1674 }
1675 }
1676
1677 /**
1678 * Get the position of the master from SHOW SLAVE STATUS
1679 */
1680 function getSlavePos() {
1681 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1682 $row = $this->fetchObject( $res );
1683 if ( $row ) {
1684 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1685 } else {
1686 return array( false, false );
1687 }
1688 }
1689
1690 /**
1691 * Get the position of the master from SHOW MASTER STATUS
1692 */
1693 function getMasterPos() {
1694 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1695 $row = $this->fetchObject( $res );
1696 if ( $row ) {
1697 return array( $row->File, $row->Position );
1698 } else {
1699 return array( false, false );
1700 }
1701 }
1702
1703 /**
1704 * Begin a transaction, committing any previously open transaction
1705 */
1706 function begin( $fname = 'Database::begin' ) {
1707 $this->query( 'BEGIN', $fname );
1708 $this->mTrxLevel = 1;
1709 }
1710
1711 /**
1712 * End a transaction
1713 */
1714 function commit( $fname = 'Database::commit' ) {
1715 $this->query( 'COMMIT', $fname );
1716 $this->mTrxLevel = 0;
1717 }
1718
1719 /**
1720 * Rollback a transaction
1721 */
1722 function rollback( $fname = 'Database::rollback' ) {
1723 $this->query( 'ROLLBACK', $fname );
1724 $this->mTrxLevel = 0;
1725 }
1726
1727 /**
1728 * Begin a transaction, committing any previously open transaction
1729 * @deprecated use begin()
1730 */
1731 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1732 $this->begin();
1733 }
1734
1735 /**
1736 * Commit transaction, if one is open
1737 * @deprecated use commit()
1738 */
1739 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1740 $this->commit();
1741 }
1742
1743 /**
1744 * Return MW-style timestamp used for MySQL schema
1745 */
1746 function timestamp( $ts=0 ) {
1747 return wfTimestamp(TS_MW,$ts);
1748 }
1749
1750 /**
1751 * Local database timestamp format or null
1752 */
1753 function timestampOrNull( $ts = null ) {
1754 if( is_null( $ts ) ) {
1755 return null;
1756 } else {
1757 return $this->timestamp( $ts );
1758 }
1759 }
1760
1761 /**
1762 * @todo document
1763 */
1764 function resultObject( $result ) {
1765 if( empty( $result ) ) {
1766 return NULL;
1767 } else {
1768 return new ResultWrapper( $this, $result );
1769 }
1770 }
1771
1772 /**
1773 * Return aggregated value alias
1774 */
1775 function aggregateValue ($valuedata,$valuename='value') {
1776 return $valuename;
1777 }
1778
1779 /**
1780 * @return string wikitext of a link to the server software's web site
1781 */
1782 function getSoftwareLink() {
1783 return "[http://www.mysql.com/ MySQL]";
1784 }
1785
1786 /**
1787 * @return string Version information from the database
1788 */
1789 function getServerVersion() {
1790 return mysql_get_server_info();
1791 }
1792
1793 /**
1794 * Ping the server and try to reconnect if it there is no connection
1795 */
1796 function ping() {
1797 if( function_exists( 'mysql_ping' ) ) {
1798 return mysql_ping( $this->mConn );
1799 } else {
1800 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1801 return true;
1802 }
1803 }
1804
1805 /**
1806 * Get slave lag.
1807 * At the moment, this will only work if the DB user has the PROCESS privilege
1808 */
1809 function getLag() {
1810 $res = $this->query( 'SHOW PROCESSLIST' );
1811 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1812 # dubious, but unfortunately there's no easy rigorous way
1813 $slaveThreads = 0;
1814 while ( $row = $this->fetchObject( $res ) ) {
1815 /* This should work for most situations - when default db
1816 * for thread is not specified, it had no events executed,
1817 * and therefore it doesn't know yet how lagged it is.
1818 *
1819 * Relay log I/O thread does not select databases.
1820 */
1821 if ( $row->User == 'system user' &&
1822 $row->State != 'Waiting for master to send event' &&
1823 $row->State != 'Connecting to master' &&
1824 $row->State != 'Queueing master event to the relay log' &&
1825 $row->State != 'Waiting for master update' &&
1826 $row->State != 'Requesting binlog dump'
1827 ) {
1828 # This is it, return the time (except -ve)
1829 if ( $row->Time > 0x7fffffff ) {
1830 return false;
1831 } else {
1832 return $row->Time;
1833 }
1834 }
1835 }
1836 return false;
1837 }
1838
1839 /**
1840 * Get status information from SHOW STATUS in an associative array
1841 */
1842 function getStatus($which="%") {
1843 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1844 $status = array();
1845 while ( $row = $this->fetchObject( $res ) ) {
1846 $status[$row->Variable_name] = $row->Value;
1847 }
1848 return $status;
1849 }
1850
1851 /**
1852 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1853 */
1854 function maxListLen() {
1855 return 0;
1856 }
1857
1858 function encodeBlob($b) {
1859 return $b;
1860 }
1861
1862 /**
1863 * Read and execute SQL commands from a file.
1864 * Returns true on success, error string on failure
1865 */
1866 function sourceFile( $filename ) {
1867 $fp = fopen( $filename, 'r' );
1868 if ( false === $fp ) {
1869 return "Could not open \"{$fname}\".\n";
1870 }
1871
1872 $cmd = "";
1873 $done = false;
1874 $dollarquote = false;
1875
1876 while ( ! feof( $fp ) ) {
1877 $line = trim( fgets( $fp, 1024 ) );
1878 $sl = strlen( $line ) - 1;
1879
1880 if ( $sl < 0 ) { continue; }
1881 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1882
1883 ## Allow dollar quoting for function declarations
1884 if (substr($line,0,4) == '$mw$') {
1885 if ($dollarquote) {
1886 $dollarquote = false;
1887 $done = true;
1888 }
1889 else {
1890 $dollarquote = true;
1891 }
1892 }
1893 else if (!$dollarquote) {
1894 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
1895 $done = true;
1896 $line = substr( $line, 0, $sl );
1897 }
1898 }
1899
1900 if ( '' != $cmd ) { $cmd .= ' '; }
1901 $cmd .= "$line\n";
1902
1903 if ( $done ) {
1904 $cmd = str_replace(';;', ";", $cmd);
1905 $cmd = $this->replaceVars( $cmd );
1906 $res = $this->query( $cmd, 'dbsource', true );
1907
1908 if ( false === $res ) {
1909 $err = $this->lastError();
1910 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1911 }
1912
1913 $cmd = '';
1914 $done = false;
1915 }
1916 }
1917 fclose( $fp );
1918 return true;
1919 }
1920
1921 /**
1922 * Replace variables in sourced SQL
1923 */
1924 protected function replaceVars( $ins ) {
1925 $varnames = array(
1926 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1927 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1928 'wgDBadminuser', 'wgDBadminpassword',
1929 );
1930
1931 // Ordinary variables
1932 foreach ( $varnames as $var ) {
1933 if( isset( $GLOBALS[$var] ) ) {
1934 $val = addslashes( $GLOBALS[$var] );
1935 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1936 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1937 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1938 }
1939 }
1940
1941 // Table prefixes
1942 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1943 array( &$this, 'tableNameCallback' ), $ins );
1944 return $ins;
1945 }
1946
1947 /**
1948 * Table name callback
1949 * @private
1950 */
1951 protected function tableNameCallback( $matches ) {
1952 return $this->tableName( $matches[1] );
1953 }
1954
1955 }
1956
1957 /**
1958 * Database abstraction object for mySQL
1959 * Inherit all methods and properties of Database::Database()
1960 *
1961 * @package MediaWiki
1962 * @see Database
1963 */
1964 class DatabaseMysql extends Database {
1965 # Inherit all
1966 }
1967
1968
1969 /**
1970 * Result wrapper for grabbing data queried by someone else
1971 *
1972 * @package MediaWiki
1973 */
1974 class ResultWrapper {
1975 var $db, $result;
1976
1977 /**
1978 * @todo document
1979 */
1980 function ResultWrapper( &$database, $result ) {
1981 $this->db =& $database;
1982 $this->result =& $result;
1983 }
1984
1985 /**
1986 * @todo document
1987 */
1988 function numRows() {
1989 return $this->db->numRows( $this->result );
1990 }
1991
1992 /**
1993 * @todo document
1994 */
1995 function fetchObject() {
1996 return $this->db->fetchObject( $this->result );
1997 }
1998
1999 /**
2000 * @todo document
2001 */
2002 function fetchRow() {
2003 return $this->db->fetchRow( $this->result );
2004 }
2005
2006 /**
2007 * @todo document
2008 */
2009 function free() {
2010 $this->db->freeResult( $this->result );
2011 unset( $this->result );
2012 unset( $this->db );
2013 }
2014
2015 function seek( $row ) {
2016 $this->db->dataSeek( $this->result, $row );
2017 }
2018
2019 }
2020
2021 ?>