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