1812cd1ec3d20d155144aa3d36d368e5fdf34885
[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 wfProfileIn( __METHOD__ );
453
454 # Test for missing mysql.so
455 # First try to load it
456 if (!@extension_loaded('mysql')) {
457 @dl('mysql.so');
458 }
459
460 # Fail now
461 # Otherwise we get a suppressed fatal error, which is very hard to track down
462 if ( !function_exists( 'mysql_connect' ) ) {
463 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
464 }
465
466 $this->close();
467 $this->mServer = $server;
468 $this->mUser = $user;
469 $this->mPassword = $password;
470 $this->mDBname = $dbName;
471
472 $success = false;
473
474 if ( $this->mFlags & DBO_PERSISTENT ) {
475 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
476 } else {
477 # Create a new connection...
478 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
479 }
480
481 if ( $dbName != '' ) {
482 if ( $this->mConn !== false ) {
483 $success = @/**/mysql_select_db( $dbName, $this->mConn );
484 if ( !$success ) {
485 $error = "Error selecting database $dbName on server {$this->mServer} " .
486 "from client host {$wguname['nodename']}\n";
487 wfDebug( $error );
488 }
489 } else {
490 wfDebug( "DB connection error\n" );
491 wfDebug( "Server: $server, User: $user, Password: " .
492 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
493 $success = false;
494 }
495 } else {
496 # Delay USE query
497 $success = (bool)$this->mConn;
498 }
499
500 if ( !$success ) {
501 $this->reportConnectionError();
502 }
503
504 global $wgDBmysql5;
505 if( $wgDBmysql5 ) {
506 // Tell the server we're communicating with it in UTF-8.
507 // This may engage various charset conversions.
508 $this->query( 'SET NAMES utf8' );
509 }
510
511 $this->mOpened = $success;
512 wfProfileOut( __METHOD__ );
513 return $success;
514 }
515 /**@}}*/
516
517 /**
518 * Closes a database connection.
519 * if it is open : commits any open transactions
520 *
521 * @return bool operation success. true if already closed.
522 */
523 function close()
524 {
525 $this->mOpened = false;
526 if ( $this->mConn ) {
527 if ( $this->trxLevel() ) {
528 $this->immediateCommit();
529 }
530 return mysql_close( $this->mConn );
531 } else {
532 return true;
533 }
534 }
535
536 /**
537 * @param string $error fallback error message, used if none is given by MySQL
538 */
539 function reportConnectionError( $error = 'Unknown error' ) {
540 $myError = $this->lastError();
541 if ( $myError ) {
542 $error = $myError;
543 }
544
545 if ( $this->mFailFunction ) {
546 # Legacy error handling method
547 if ( !is_int( $this->mFailFunction ) ) {
548 $ff = $this->mFailFunction;
549 $ff( $this, $error );
550 }
551 } else {
552 # New method
553 wfLogDBError( "Connection error: $error\n" );
554 throw new DBConnectionError( $this, $error );
555 }
556 }
557
558 /**
559 * Usually aborts on failure
560 * If errors are explicitly ignored, returns success
561 */
562 function query( $sql, $fname = '', $tempIgnore = false ) {
563 global $wgProfiling;
564
565 if ( $wgProfiling ) {
566 # generalizeSQL will probably cut down the query to reasonable
567 # logging size most of the time. The substr is really just a sanity check.
568
569 # Who's been wasting my precious column space? -- TS
570 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
571
572 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
573 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
574 $totalProf = 'Database::query';
575 } else {
576 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
577 $totalProf = 'Database::query-master';
578 }
579 wfProfileIn( $totalProf );
580 wfProfileIn( $queryProf );
581 }
582
583 $this->mLastQuery = $sql;
584
585 # Add a comment for easy SHOW PROCESSLIST interpretation
586 if ( $fname ) {
587 $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
588 } else {
589 $commentedSql = $sql;
590 }
591
592 # If DBO_TRX is set, start a transaction
593 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
594 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
595 ) {
596 $this->begin();
597 }
598
599 if ( $this->debug() ) {
600 $sqlx = substr( $commentedSql, 0, 500 );
601 $sqlx = strtr( $sqlx, "\t\n", ' ' );
602 wfDebug( "SQL: $sqlx\n" );
603 }
604
605 # Do the query and handle errors
606 $ret = $this->doQuery( $commentedSql );
607
608 # Try reconnecting if the connection was lost
609 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
610 # Transaction is gone, like it or not
611 $this->mTrxLevel = 0;
612 wfDebug( "Connection lost, reconnecting...\n" );
613 if ( $this->ping() ) {
614 wfDebug( "Reconnected\n" );
615 $ret = $this->doQuery( $commentedSql );
616 } else {
617 wfDebug( "Failed\n" );
618 }
619 }
620
621 if ( false === $ret ) {
622 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
623 }
624
625 if ( $wgProfiling ) {
626 wfProfileOut( $queryProf );
627 wfProfileOut( $totalProf );
628 }
629 return $ret;
630 }
631
632 /**
633 * The DBMS-dependent part of query()
634 * @param string $sql SQL query.
635 */
636 function doQuery( $sql ) {
637 if( $this->bufferResults() ) {
638 $ret = mysql_query( $sql, $this->mConn );
639 } else {
640 $ret = mysql_unbuffered_query( $sql, $this->mConn );
641 }
642 return $ret;
643 }
644
645 /**
646 * @param $error
647 * @param $errno
648 * @param $sql
649 * @param string $fname
650 * @param bool $tempIgnore
651 */
652 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
653 global $wgCommandLineMode, $wgFullyInitialised, $wgColorErrors;
654 # Ignore errors during error handling to avoid infinite recursion
655 $ignore = $this->ignoreErrors( true );
656 ++$this->mErrorCount;
657
658 if( $ignore || $tempIgnore ) {
659 wfDebug("SQL ERROR (ignored): $error\n");
660 $this->ignoreErrors( $ignore );
661 } else {
662 $sql1line = str_replace( "\n", "\\n", $sql );
663 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
664 wfDebug("SQL ERROR: " . $error . "\n");
665 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
666 }
667 }
668
669
670 /**
671 * Intended to be compatible with the PEAR::DB wrapper functions.
672 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
673 *
674 * ? = scalar value, quoted as necessary
675 * ! = raw SQL bit (a function for instance)
676 * & = filename; reads the file and inserts as a blob
677 * (we don't use this though...)
678 */
679 function prepare( $sql, $func = 'Database::prepare' ) {
680 /* MySQL doesn't support prepared statements (yet), so just
681 pack up the query for reference. We'll manually replace
682 the bits later. */
683 return array( 'query' => $sql, 'func' => $func );
684 }
685
686 function freePrepared( $prepared ) {
687 /* No-op for MySQL */
688 }
689
690 /**
691 * Execute a prepared query with the various arguments
692 * @param string $prepared the prepared sql
693 * @param mixed $args Either an array here, or put scalars as varargs
694 */
695 function execute( $prepared, $args = null ) {
696 if( !is_array( $args ) ) {
697 # Pull the var args
698 $args = func_get_args();
699 array_shift( $args );
700 }
701 $sql = $this->fillPrepared( $prepared['query'], $args );
702 return $this->query( $sql, $prepared['func'] );
703 }
704
705 /**
706 * Prepare & execute an SQL statement, quoting and inserting arguments
707 * in the appropriate places.
708 * @param string $query
709 * @param string $args ...
710 */
711 function safeQuery( $query, $args = null ) {
712 $prepared = $this->prepare( $query, 'Database::safeQuery' );
713 if( !is_array( $args ) ) {
714 # Pull the var args
715 $args = func_get_args();
716 array_shift( $args );
717 }
718 $retval = $this->execute( $prepared, $args );
719 $this->freePrepared( $prepared );
720 return $retval;
721 }
722
723 /**
724 * For faking prepared SQL statements on DBs that don't support
725 * it directly.
726 * @param string $preparedSql - a 'preparable' SQL statement
727 * @param array $args - array of arguments to fill it with
728 * @return string executable SQL
729 */
730 function fillPrepared( $preparedQuery, $args ) {
731 reset( $args );
732 $this->preparedArgs =& $args;
733 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
734 array( &$this, 'fillPreparedArg' ), $preparedQuery );
735 }
736
737 /**
738 * preg_callback func for fillPrepared()
739 * The arguments should be in $this->preparedArgs and must not be touched
740 * while we're doing this.
741 *
742 * @param array $matches
743 * @return string
744 * @private
745 */
746 function fillPreparedArg( $matches ) {
747 switch( $matches[1] ) {
748 case '\\?': return '?';
749 case '\\!': return '!';
750 case '\\&': return '&';
751 }
752 list( $n, $arg ) = each( $this->preparedArgs );
753 switch( $matches[1] ) {
754 case '?': return $this->addQuotes( $arg );
755 case '!': return $arg;
756 case '&':
757 # return $this->addQuotes( file_get_contents( $arg ) );
758 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
759 default:
760 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
761 }
762 }
763
764 /**#@+
765 * @param mixed $res A SQL result
766 */
767 /**
768 * Free a result object
769 */
770 function freeResult( $res ) {
771 if ( !@/**/mysql_free_result( $res ) ) {
772 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
773 }
774 }
775
776 /**
777 * Fetch the next row from the given result object, in object form
778 */
779 function fetchObject( $res ) {
780 @/**/$row = mysql_fetch_object( $res );
781 if( $this->lastErrno() ) {
782 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
783 }
784 return $row;
785 }
786
787 /**
788 * Fetch the next row from the given result object
789 * Returns an array
790 */
791 function fetchRow( $res ) {
792 @/**/$row = mysql_fetch_array( $res );
793 if ( $this->lastErrno() ) {
794 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
795 }
796 return $row;
797 }
798
799 /**
800 * Get the number of rows in a result object
801 */
802 function numRows( $res ) {
803 @/**/$n = mysql_num_rows( $res );
804 if( $this->lastErrno() ) {
805 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
806 }
807 return $n;
808 }
809
810 /**
811 * Get the number of fields in a result object
812 * See documentation for mysql_num_fields()
813 */
814 function numFields( $res ) { return mysql_num_fields( $res ); }
815
816 /**
817 * Get a field name in a result object
818 * See documentation for mysql_field_name():
819 * http://www.php.net/mysql_field_name
820 */
821 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
822
823 /**
824 * Get the inserted value of an auto-increment row
825 *
826 * The value inserted should be fetched from nextSequenceValue()
827 *
828 * Example:
829 * $id = $dbw->nextSequenceValue('page_page_id_seq');
830 * $dbw->insert('page',array('page_id' => $id));
831 * $id = $dbw->insertId();
832 */
833 function insertId() { return mysql_insert_id( $this->mConn ); }
834
835 /**
836 * Change the position of the cursor in a result object
837 * See mysql_data_seek()
838 */
839 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
840
841 /**
842 * Get the last error number
843 * See mysql_errno()
844 */
845 function lastErrno() {
846 if ( $this->mConn ) {
847 return mysql_errno( $this->mConn );
848 } else {
849 return mysql_errno();
850 }
851 }
852
853 /**
854 * Get a description of the last error
855 * See mysql_error() for more details
856 */
857 function lastError() {
858 if ( $this->mConn ) {
859 # Even if it's non-zero, it can still be invalid
860 wfSuppressWarnings();
861 $error = mysql_error( $this->mConn );
862 if ( !$error ) {
863 $error = mysql_error();
864 }
865 wfRestoreWarnings();
866 } else {
867 $error = mysql_error();
868 }
869 if( $error ) {
870 $error .= ' (' . $this->mServer . ')';
871 }
872 return $error;
873 }
874 /**
875 * Get the number of rows affected by the last write query
876 * See mysql_affected_rows() for more details
877 */
878 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
879 /**#@-*/ // end of template : @param $result
880
881 /**
882 * Simple UPDATE wrapper
883 * Usually aborts on failure
884 * If errors are explicitly ignored, returns success
885 *
886 * This function exists for historical reasons, Database::update() has a more standard
887 * calling convention and feature set
888 */
889 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
890 {
891 $table = $this->tableName( $table );
892 $sql = "UPDATE $table SET $var = '" .
893 $this->strencode( $value ) . "' WHERE ($cond)";
894 return (bool)$this->query( $sql, $fname );
895 }
896
897 /**
898 * Simple SELECT wrapper, returns a single field, input must be encoded
899 * Usually aborts on failure
900 * If errors are explicitly ignored, returns FALSE on failure
901 */
902 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
903 if ( !is_array( $options ) ) {
904 $options = array( $options );
905 }
906 $options['LIMIT'] = 1;
907
908 $res = $this->select( $table, $var, $cond, $fname, $options );
909 if ( $res === false || !$this->numRows( $res ) ) {
910 return false;
911 }
912 $row = $this->fetchRow( $res );
913 if ( $row !== false ) {
914 $this->freeResult( $res );
915 return $row[0];
916 } else {
917 return false;
918 }
919 }
920
921 /**
922 * Returns an optional USE INDEX clause to go after the table, and a
923 * string to go at the end of the query
924 *
925 * @private
926 *
927 * @param array $options an associative array of options to be turned into
928 * an SQL query, valid keys are listed in the function.
929 * @return array
930 */
931 function makeSelectOptions( $options ) {
932 $tailOpts = '';
933 $startOpts = '';
934
935 $noKeyOptions = array();
936 foreach ( $options as $key => $option ) {
937 if ( is_numeric( $key ) ) {
938 $noKeyOptions[$option] = true;
939 }
940 }
941
942 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
943 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
944
945 if (isset($options['LIMIT'])) {
946 $tailOpts .= $this->limitResult('', $options['LIMIT'],
947 isset($options['OFFSET']) ? $options['OFFSET'] : false);
948 }
949
950 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
951 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
952 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
953
954 # Various MySQL extensions
955 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
956 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
957 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
958 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
959 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
960 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
961 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
962
963 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
964 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
965 } else {
966 $useIndex = '';
967 }
968
969 return array( $startOpts, $useIndex, $tailOpts );
970 }
971
972 /**
973 * SELECT wrapper
974 */
975 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
976 {
977 if( is_array( $vars ) ) {
978 $vars = implode( ',', $vars );
979 }
980 if( !is_array( $options ) ) {
981 $options = array( $options );
982 }
983 if( is_array( $table ) ) {
984 if ( @is_array( $options['USE INDEX'] ) )
985 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
986 else
987 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
988 } elseif ($table!='') {
989 $from = ' FROM ' . $this->tableName( $table );
990 } else {
991 $from = '';
992 }
993
994 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
995
996 if( !empty( $conds ) ) {
997 if ( is_array( $conds ) ) {
998 $conds = $this->makeList( $conds, LIST_AND );
999 }
1000 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $tailOpts";
1001 } else {
1002 $sql = "SELECT $startOpts $vars $from $useIndex $tailOpts";
1003 }
1004
1005 return $this->query( $sql, $fname );
1006 }
1007
1008 /**
1009 * Single row SELECT wrapper
1010 * Aborts or returns FALSE on error
1011 *
1012 * $vars: the selected variables
1013 * $conds: a condition map, terms are ANDed together.
1014 * Items with numeric keys are taken to be literal conditions
1015 * Takes an array of selected variables, and a condition map, which is ANDed
1016 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1017 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1018 * $obj- >page_id is the ID of the Astronomy article
1019 *
1020 * @todo migrate documentation to phpdocumentor format
1021 */
1022 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1023 $options['LIMIT'] = 1;
1024 $res = $this->select( $table, $vars, $conds, $fname, $options );
1025 if ( $res === false )
1026 return false;
1027 if ( !$this->numRows($res) ) {
1028 $this->freeResult($res);
1029 return false;
1030 }
1031 $obj = $this->fetchObject( $res );
1032 $this->freeResult( $res );
1033 return $obj;
1034
1035 }
1036
1037 /**
1038 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1039 * It's only slightly flawed. Don't use for anything important.
1040 *
1041 * @param string $sql A SQL Query
1042 * @static
1043 */
1044 static function generalizeSQL( $sql ) {
1045 # This does the same as the regexp below would do, but in such a way
1046 # as to avoid crashing php on some large strings.
1047 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1048
1049 $sql = str_replace ( "\\\\", '', $sql);
1050 $sql = str_replace ( "\\'", '', $sql);
1051 $sql = str_replace ( "\\\"", '', $sql);
1052 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1053 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1054
1055 # All newlines, tabs, etc replaced by single space
1056 $sql = preg_replace ( "/\s+/", ' ', $sql);
1057
1058 # All numbers => N
1059 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1060
1061 return $sql;
1062 }
1063
1064 /**
1065 * Determines whether a field exists in a table
1066 * Usually aborts on failure
1067 * If errors are explicitly ignored, returns NULL on failure
1068 */
1069 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1070 $table = $this->tableName( $table );
1071 $res = $this->query( 'DESCRIBE '.$table, $fname );
1072 if ( !$res ) {
1073 return NULL;
1074 }
1075
1076 $found = false;
1077
1078 while ( $row = $this->fetchObject( $res ) ) {
1079 if ( $row->Field == $field ) {
1080 $found = true;
1081 break;
1082 }
1083 }
1084 return $found;
1085 }
1086
1087 /**
1088 * Determines whether an index exists
1089 * Usually aborts on failure
1090 * If errors are explicitly ignored, returns NULL on failure
1091 */
1092 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1093 $info = $this->indexInfo( $table, $index, $fname );
1094 if ( is_null( $info ) ) {
1095 return NULL;
1096 } else {
1097 return $info !== false;
1098 }
1099 }
1100
1101
1102 /**
1103 * Get information about an index into an object
1104 * Returns false if the index does not exist
1105 */
1106 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1107 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1108 # SHOW INDEX should work for 3.x and up:
1109 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1110 $table = $this->tableName( $table );
1111 $sql = 'SHOW INDEX FROM '.$table;
1112 $res = $this->query( $sql, $fname );
1113 if ( !$res ) {
1114 return NULL;
1115 }
1116
1117 while ( $row = $this->fetchObject( $res ) ) {
1118 if ( $row->Key_name == $index ) {
1119 return $row;
1120 }
1121 }
1122 return false;
1123 }
1124
1125 /**
1126 * Query whether a given table exists
1127 */
1128 function tableExists( $table ) {
1129 $table = $this->tableName( $table );
1130 $old = $this->ignoreErrors( true );
1131 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1132 $this->ignoreErrors( $old );
1133 if( $res ) {
1134 $this->freeResult( $res );
1135 return true;
1136 } else {
1137 return false;
1138 }
1139 }
1140
1141 /**
1142 * mysql_fetch_field() wrapper
1143 * Returns false if the field doesn't exist
1144 *
1145 * @param $table
1146 * @param $field
1147 */
1148 function fieldInfo( $table, $field ) {
1149 $table = $this->tableName( $table );
1150 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1151 $n = mysql_num_fields( $res );
1152 for( $i = 0; $i < $n; $i++ ) {
1153 $meta = mysql_fetch_field( $res, $i );
1154 if( $field == $meta->name ) {
1155 return $meta;
1156 }
1157 }
1158 return false;
1159 }
1160
1161 /**
1162 * mysql_field_type() wrapper
1163 */
1164 function fieldType( $res, $index ) {
1165 return mysql_field_type( $res, $index );
1166 }
1167
1168 /**
1169 * Determines if a given index is unique
1170 */
1171 function indexUnique( $table, $index ) {
1172 $indexInfo = $this->indexInfo( $table, $index );
1173 if ( !$indexInfo ) {
1174 return NULL;
1175 }
1176 return !$indexInfo->Non_unique;
1177 }
1178
1179 /**
1180 * INSERT wrapper, inserts an array into a table
1181 *
1182 * $a may be a single associative array, or an array of these with numeric keys, for
1183 * multi-row insert.
1184 *
1185 * Usually aborts on failure
1186 * If errors are explicitly ignored, returns success
1187 */
1188 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1189 # No rows to insert, easy just return now
1190 if ( !count( $a ) ) {
1191 return true;
1192 }
1193
1194 $table = $this->tableName( $table );
1195 if ( !is_array( $options ) ) {
1196 $options = array( $options );
1197 }
1198 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1199 $multi = true;
1200 $keys = array_keys( $a[0] );
1201 } else {
1202 $multi = false;
1203 $keys = array_keys( $a );
1204 }
1205
1206 $sql = 'INSERT ' . implode( ' ', $options ) .
1207 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1208
1209 if ( $multi ) {
1210 $first = true;
1211 foreach ( $a as $row ) {
1212 if ( $first ) {
1213 $first = false;
1214 } else {
1215 $sql .= ',';
1216 }
1217 $sql .= '(' . $this->makeList( $row ) . ')';
1218 }
1219 } else {
1220 $sql .= '(' . $this->makeList( $a ) . ')';
1221 }
1222 return (bool)$this->query( $sql, $fname );
1223 }
1224
1225 /**
1226 * Make UPDATE options for the Database::update function
1227 *
1228 * @private
1229 * @param array $options The options passed to Database::update
1230 * @return string
1231 */
1232 function makeUpdateOptions( $options ) {
1233 if( !is_array( $options ) ) {
1234 $options = array( $options );
1235 }
1236 $opts = array();
1237 if ( in_array( 'LOW_PRIORITY', $options ) )
1238 $opts[] = $this->lowPriorityOption();
1239 if ( in_array( 'IGNORE', $options ) )
1240 $opts[] = 'IGNORE';
1241 return implode(' ', $opts);
1242 }
1243
1244 /**
1245 * UPDATE wrapper, takes a condition array and a SET array
1246 *
1247 * @param string $table The table to UPDATE
1248 * @param array $values An array of values to SET
1249 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1250 * @param string $fname The Class::Function calling this function
1251 * (for the log)
1252 * @param array $options An array of UPDATE options, can be one or
1253 * more of IGNORE, LOW_PRIORITY
1254 */
1255 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1256 $table = $this->tableName( $table );
1257 $opts = $this->makeUpdateOptions( $options );
1258 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1259 if ( $conds != '*' ) {
1260 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1261 }
1262 $this->query( $sql, $fname );
1263 }
1264
1265 /**
1266 * Makes a wfStrencoded list from an array
1267 * $mode:
1268 * LIST_COMMA - comma separated, no field names
1269 * LIST_AND - ANDed WHERE clause (without the WHERE)
1270 * LIST_OR - ORed WHERE clause (without the WHERE)
1271 * LIST_SET - comma separated with field names, like a SET clause
1272 * LIST_NAMES - comma separated field names
1273 */
1274 function makeList( $a, $mode = LIST_COMMA ) {
1275 if ( !is_array( $a ) ) {
1276 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1277 }
1278
1279 $first = true;
1280 $list = '';
1281 foreach ( $a as $field => $value ) {
1282 if ( !$first ) {
1283 if ( $mode == LIST_AND ) {
1284 $list .= ' AND ';
1285 } elseif($mode == LIST_OR) {
1286 $list .= ' OR ';
1287 } else {
1288 $list .= ',';
1289 }
1290 } else {
1291 $first = false;
1292 }
1293 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1294 $list .= "($value)";
1295 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1296 $list .= $field." IN (".$this->makeList($value).") ";
1297 } else {
1298 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1299 $list .= "$field = ";
1300 }
1301 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1302 }
1303 }
1304 return $list;
1305 }
1306
1307 /**
1308 * Change the current database
1309 */
1310 function selectDB( $db ) {
1311 $this->mDBname = $db;
1312 return mysql_select_db( $db, $this->mConn );
1313 }
1314
1315 /**
1316 * Format a table name ready for use in constructing an SQL query
1317 *
1318 * This does two important things: it quotes table names which as necessary,
1319 * and it adds a table prefix if there is one.
1320 *
1321 * All functions of this object which require a table name call this function
1322 * themselves. Pass the canonical name to such functions. This is only needed
1323 * when calling query() directly.
1324 *
1325 * @param string $name database table name
1326 */
1327 function tableName( $name ) {
1328 global $wgSharedDB;
1329 # Skip quoted literals
1330 if ( $name{0} != '`' ) {
1331 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1332 $name = "{$this->mTablePrefix}$name";
1333 }
1334 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1335 $name = "`$wgSharedDB`.`$name`";
1336 } else {
1337 # Standard quoting
1338 $name = "`$name`";
1339 }
1340 }
1341 return $name;
1342 }
1343
1344 /**
1345 * Fetch a number of table names into an array
1346 * This is handy when you need to construct SQL for joins
1347 *
1348 * Example:
1349 * extract($dbr->tableNames('user','watchlist'));
1350 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1351 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1352 */
1353 function tableNames() {
1354 $inArray = func_get_args();
1355 $retVal = array();
1356 foreach ( $inArray as $name ) {
1357 $retVal[$name] = $this->tableName( $name );
1358 }
1359 return $retVal;
1360 }
1361
1362 /**
1363 * @private
1364 */
1365 function tableNamesWithUseIndex( $tables, $use_index ) {
1366 $ret = array();
1367
1368 foreach ( $tables as $table )
1369 if ( @$use_index[$table] !== null )
1370 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1371 else
1372 $ret[] = $this->tableName( $table );
1373
1374 return implode( ',', $ret );
1375 }
1376
1377 /**
1378 * Wrapper for addslashes()
1379 * @param string $s String to be slashed.
1380 * @return string slashed string.
1381 */
1382 function strencode( $s ) {
1383 return mysql_real_escape_string( $s, $this->mConn );
1384 }
1385
1386 /**
1387 * If it's a string, adds quotes and backslashes
1388 * Otherwise returns as-is
1389 */
1390 function addQuotes( $s ) {
1391 if ( is_null( $s ) ) {
1392 return 'NULL';
1393 } else {
1394 # This will also quote numeric values. This should be harmless,
1395 # and protects against weird problems that occur when they really
1396 # _are_ strings such as article titles and string->number->string
1397 # conversion is not 1:1.
1398 return "'" . $this->strencode( $s ) . "'";
1399 }
1400 }
1401
1402 /**
1403 * Escape string for safe LIKE usage
1404 */
1405 function escapeLike( $s ) {
1406 $s=$this->strencode( $s );
1407 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1408 return $s;
1409 }
1410
1411 /**
1412 * Returns an appropriately quoted sequence value for inserting a new row.
1413 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1414 * subclass will return an integer, and save the value for insertId()
1415 */
1416 function nextSequenceValue( $seqName ) {
1417 return NULL;
1418 }
1419
1420 /**
1421 * USE INDEX clause
1422 * PostgreSQL doesn't have them and returns ""
1423 */
1424 function useIndexClause( $index ) {
1425 return "FORCE INDEX ($index)";
1426 }
1427
1428 /**
1429 * REPLACE query wrapper
1430 * PostgreSQL simulates this with a DELETE followed by INSERT
1431 * $row is the row to insert, an associative array
1432 * $uniqueIndexes is an array of indexes. Each element may be either a
1433 * field name or an array of field names
1434 *
1435 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1436 * However if you do this, you run the risk of encountering errors which wouldn't have
1437 * occurred in MySQL
1438 *
1439 * @todo migrate comment to phodocumentor format
1440 */
1441 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1442 $table = $this->tableName( $table );
1443
1444 # Single row case
1445 if ( !is_array( reset( $rows ) ) ) {
1446 $rows = array( $rows );
1447 }
1448
1449 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1450 $first = true;
1451 foreach ( $rows as $row ) {
1452 if ( $first ) {
1453 $first = false;
1454 } else {
1455 $sql .= ',';
1456 }
1457 $sql .= '(' . $this->makeList( $row ) . ')';
1458 }
1459 return $this->query( $sql, $fname );
1460 }
1461
1462 /**
1463 * DELETE where the condition is a join
1464 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1465 *
1466 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1467 * join condition matches, set $conds='*'
1468 *
1469 * DO NOT put the join condition in $conds
1470 *
1471 * @param string $delTable The table to delete from.
1472 * @param string $joinTable The other table.
1473 * @param string $delVar The variable to join on, in the first table.
1474 * @param string $joinVar The variable to join on, in the second table.
1475 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1476 */
1477 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1478 if ( !$conds ) {
1479 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1480 }
1481
1482 $delTable = $this->tableName( $delTable );
1483 $joinTable = $this->tableName( $joinTable );
1484 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1485 if ( $conds != '*' ) {
1486 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1487 }
1488
1489 return $this->query( $sql, $fname );
1490 }
1491
1492 /**
1493 * Returns the size of a text field, or -1 for "unlimited"
1494 */
1495 function textFieldSize( $table, $field ) {
1496 $table = $this->tableName( $table );
1497 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1498 $res = $this->query( $sql, 'Database::textFieldSize' );
1499 $row = $this->fetchObject( $res );
1500 $this->freeResult( $res );
1501
1502 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1503 $size = $m[1];
1504 } else {
1505 $size = -1;
1506 }
1507 return $size;
1508 }
1509
1510 /**
1511 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1512 */
1513 function lowPriorityOption() {
1514 return 'LOW_PRIORITY';
1515 }
1516
1517 /**
1518 * DELETE query wrapper
1519 *
1520 * Use $conds == "*" to delete all rows
1521 */
1522 function delete( $table, $conds, $fname = 'Database::delete' ) {
1523 if ( !$conds ) {
1524 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1525 }
1526 $table = $this->tableName( $table );
1527 $sql = "DELETE FROM $table";
1528 if ( $conds != '*' ) {
1529 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1530 }
1531 return $this->query( $sql, $fname );
1532 }
1533
1534 /**
1535 * INSERT SELECT wrapper
1536 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1537 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1538 * $conds may be "*" to copy the whole table
1539 * srcTable may be an array of tables.
1540 */
1541 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1542 $insertOptions = array(), $selectOptions = array() )
1543 {
1544 $destTable = $this->tableName( $destTable );
1545 if ( is_array( $insertOptions ) ) {
1546 $insertOptions = implode( ' ', $insertOptions );
1547 }
1548 if( !is_array( $selectOptions ) ) {
1549 $selectOptions = array( $selectOptions );
1550 }
1551 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1552 if( is_array( $srcTable ) ) {
1553 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1554 } else {
1555 $srcTable = $this->tableName( $srcTable );
1556 }
1557 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1558 " SELECT $startOpts " . implode( ',', $varMap ) .
1559 " FROM $srcTable $useIndex ";
1560 if ( $conds != '*' ) {
1561 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1562 }
1563 $sql .= " $tailOpts";
1564 return $this->query( $sql, $fname );
1565 }
1566
1567 /**
1568 * Construct a LIMIT query with optional offset
1569 * This is used for query pages
1570 * $sql string SQL query we will append the limit too
1571 * $limit integer the SQL limit
1572 * $offset integer the SQL offset (default false)
1573 */
1574 function limitResult($sql, $limit, $offset=false) {
1575 if( !is_numeric($limit) ) {
1576 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1577 }
1578 return " $sql LIMIT "
1579 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1580 . "{$limit} ";
1581 }
1582 function limitResultForUpdate($sql, $num) {
1583 return $this->limitResult($sql, $num, 0);
1584 }
1585
1586 /**
1587 * Returns an SQL expression for a simple conditional.
1588 * Uses IF on MySQL.
1589 *
1590 * @param string $cond SQL expression which will result in a boolean value
1591 * @param string $trueVal SQL expression to return if true
1592 * @param string $falseVal SQL expression to return if false
1593 * @return string SQL fragment
1594 */
1595 function conditional( $cond, $trueVal, $falseVal ) {
1596 return " IF($cond, $trueVal, $falseVal) ";
1597 }
1598
1599 /**
1600 * Determines if the last failure was due to a deadlock
1601 */
1602 function wasDeadlock() {
1603 return $this->lastErrno() == 1213;
1604 }
1605
1606 /**
1607 * Perform a deadlock-prone transaction.
1608 *
1609 * This function invokes a callback function to perform a set of write
1610 * queries. If a deadlock occurs during the processing, the transaction
1611 * will be rolled back and the callback function will be called again.
1612 *
1613 * Usage:
1614 * $dbw->deadlockLoop( callback, ... );
1615 *
1616 * Extra arguments are passed through to the specified callback function.
1617 *
1618 * Returns whatever the callback function returned on its successful,
1619 * iteration, or false on error, for example if the retry limit was
1620 * reached.
1621 */
1622 function deadlockLoop() {
1623 $myFname = 'Database::deadlockLoop';
1624
1625 $this->begin();
1626 $args = func_get_args();
1627 $function = array_shift( $args );
1628 $oldIgnore = $this->ignoreErrors( true );
1629 $tries = DEADLOCK_TRIES;
1630 if ( is_array( $function ) ) {
1631 $fname = $function[0];
1632 } else {
1633 $fname = $function;
1634 }
1635 do {
1636 $retVal = call_user_func_array( $function, $args );
1637 $error = $this->lastError();
1638 $errno = $this->lastErrno();
1639 $sql = $this->lastQuery();
1640
1641 if ( $errno ) {
1642 if ( $this->wasDeadlock() ) {
1643 # Retry
1644 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1645 } else {
1646 $this->reportQueryError( $error, $errno, $sql, $fname );
1647 }
1648 }
1649 } while( $this->wasDeadlock() && --$tries > 0 );
1650 $this->ignoreErrors( $oldIgnore );
1651 if ( $tries <= 0 ) {
1652 $this->query( 'ROLLBACK', $myFname );
1653 $this->reportQueryError( $error, $errno, $sql, $fname );
1654 return false;
1655 } else {
1656 $this->query( 'COMMIT', $myFname );
1657 return $retVal;
1658 }
1659 }
1660
1661 /**
1662 * Do a SELECT MASTER_POS_WAIT()
1663 *
1664 * @param string $file the binlog file
1665 * @param string $pos the binlog position
1666 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1667 */
1668 function masterPosWait( $file, $pos, $timeout ) {
1669 $fname = 'Database::masterPosWait';
1670 wfProfileIn( $fname );
1671
1672
1673 # Commit any open transactions
1674 $this->immediateCommit();
1675
1676 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1677 $encFile = $this->strencode( $file );
1678 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1679 $res = $this->doQuery( $sql );
1680 if ( $res && $row = $this->fetchRow( $res ) ) {
1681 $this->freeResult( $res );
1682 wfProfileOut( $fname );
1683 return $row[0];
1684 } else {
1685 wfProfileOut( $fname );
1686 return false;
1687 }
1688 }
1689
1690 /**
1691 * Get the position of the master from SHOW SLAVE STATUS
1692 */
1693 function getSlavePos() {
1694 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1695 $row = $this->fetchObject( $res );
1696 if ( $row ) {
1697 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1698 } else {
1699 return array( false, false );
1700 }
1701 }
1702
1703 /**
1704 * Get the position of the master from SHOW MASTER STATUS
1705 */
1706 function getMasterPos() {
1707 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1708 $row = $this->fetchObject( $res );
1709 if ( $row ) {
1710 return array( $row->File, $row->Position );
1711 } else {
1712 return array( false, false );
1713 }
1714 }
1715
1716 /**
1717 * Begin a transaction, committing any previously open transaction
1718 */
1719 function begin( $fname = 'Database::begin' ) {
1720 $this->query( 'BEGIN', $fname );
1721 $this->mTrxLevel = 1;
1722 }
1723
1724 /**
1725 * End a transaction
1726 */
1727 function commit( $fname = 'Database::commit' ) {
1728 $this->query( 'COMMIT', $fname );
1729 $this->mTrxLevel = 0;
1730 }
1731
1732 /**
1733 * Rollback a transaction
1734 */
1735 function rollback( $fname = 'Database::rollback' ) {
1736 $this->query( 'ROLLBACK', $fname );
1737 $this->mTrxLevel = 0;
1738 }
1739
1740 /**
1741 * Begin a transaction, committing any previously open transaction
1742 * @deprecated use begin()
1743 */
1744 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1745 $this->begin();
1746 }
1747
1748 /**
1749 * Commit transaction, if one is open
1750 * @deprecated use commit()
1751 */
1752 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1753 $this->commit();
1754 }
1755
1756 /**
1757 * Return MW-style timestamp used for MySQL schema
1758 */
1759 function timestamp( $ts=0 ) {
1760 return wfTimestamp(TS_MW,$ts);
1761 }
1762
1763 /**
1764 * Local database timestamp format or null
1765 */
1766 function timestampOrNull( $ts = null ) {
1767 if( is_null( $ts ) ) {
1768 return null;
1769 } else {
1770 return $this->timestamp( $ts );
1771 }
1772 }
1773
1774 /**
1775 * @todo document
1776 */
1777 function resultObject( $result ) {
1778 if( empty( $result ) ) {
1779 return NULL;
1780 } else {
1781 return new ResultWrapper( $this, $result );
1782 }
1783 }
1784
1785 /**
1786 * Return aggregated value alias
1787 */
1788 function aggregateValue ($valuedata,$valuename='value') {
1789 return $valuename;
1790 }
1791
1792 /**
1793 * @return string wikitext of a link to the server software's web site
1794 */
1795 function getSoftwareLink() {
1796 return "[http://www.mysql.com/ MySQL]";
1797 }
1798
1799 /**
1800 * @return string Version information from the database
1801 */
1802 function getServerVersion() {
1803 return mysql_get_server_info();
1804 }
1805
1806 /**
1807 * Ping the server and try to reconnect if it there is no connection
1808 */
1809 function ping() {
1810 if( function_exists( 'mysql_ping' ) ) {
1811 return mysql_ping( $this->mConn );
1812 } else {
1813 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1814 return true;
1815 }
1816 }
1817
1818 /**
1819 * Get slave lag.
1820 * At the moment, this will only work if the DB user has the PROCESS privilege
1821 */
1822 function getLag() {
1823 $res = $this->query( 'SHOW PROCESSLIST' );
1824 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1825 # dubious, but unfortunately there's no easy rigorous way
1826 $slaveThreads = 0;
1827 while ( $row = $this->fetchObject( $res ) ) {
1828 /* This should work for most situations - when default db
1829 * for thread is not specified, it had no events executed,
1830 * and therefore it doesn't know yet how lagged it is.
1831 *
1832 * Relay log I/O thread does not select databases.
1833 */
1834 if ( $row->User == 'system user' &&
1835 $row->State != 'Waiting for master to send event' &&
1836 $row->State != 'Connecting to master' &&
1837 $row->State != 'Queueing master event to the relay log' &&
1838 $row->State != 'Waiting for master update' &&
1839 $row->State != 'Requesting binlog dump'
1840 ) {
1841 # This is it, return the time (except -ve)
1842 if ( $row->Time > 0x7fffffff ) {
1843 return false;
1844 } else {
1845 return $row->Time;
1846 }
1847 }
1848 }
1849 return false;
1850 }
1851
1852 /**
1853 * Get status information from SHOW STATUS in an associative array
1854 */
1855 function getStatus($which="%") {
1856 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1857 $status = array();
1858 while ( $row = $this->fetchObject( $res ) ) {
1859 $status[$row->Variable_name] = $row->Value;
1860 }
1861 return $status;
1862 }
1863
1864 /**
1865 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1866 */
1867 function maxListLen() {
1868 return 0;
1869 }
1870
1871 function encodeBlob($b) {
1872 return $b;
1873 }
1874
1875 function decodeBlob($b) {
1876 return $b;
1877 }
1878
1879 /**
1880 * Read and execute SQL commands from a file.
1881 * Returns true on success, error string on failure
1882 */
1883 function sourceFile( $filename ) {
1884 $fp = fopen( $filename, 'r' );
1885 if ( false === $fp ) {
1886 return "Could not open \"{$fname}\".\n";
1887 }
1888
1889 $cmd = "";
1890 $done = false;
1891 $dollarquote = false;
1892
1893 while ( ! feof( $fp ) ) {
1894 $line = trim( fgets( $fp, 1024 ) );
1895 $sl = strlen( $line ) - 1;
1896
1897 if ( $sl < 0 ) { continue; }
1898 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
1899
1900 ## Allow dollar quoting for function declarations
1901 if (substr($line,0,4) == '$mw$') {
1902 if ($dollarquote) {
1903 $dollarquote = false;
1904 $done = true;
1905 }
1906 else {
1907 $dollarquote = true;
1908 }
1909 }
1910 else if (!$dollarquote) {
1911 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
1912 $done = true;
1913 $line = substr( $line, 0, $sl );
1914 }
1915 }
1916
1917 if ( '' != $cmd ) { $cmd .= ' '; }
1918 $cmd .= "$line\n";
1919
1920 if ( $done ) {
1921 $cmd = str_replace(';;', ";", $cmd);
1922 $cmd = $this->replaceVars( $cmd );
1923 $res = $this->query( $cmd, 'dbsource', true );
1924
1925 if ( false === $res ) {
1926 $err = $this->lastError();
1927 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1928 }
1929
1930 $cmd = '';
1931 $done = false;
1932 }
1933 }
1934 fclose( $fp );
1935 return true;
1936 }
1937
1938 /**
1939 * Replace variables in sourced SQL
1940 */
1941 protected function replaceVars( $ins ) {
1942 $varnames = array(
1943 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
1944 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
1945 'wgDBadminuser', 'wgDBadminpassword',
1946 );
1947
1948 // Ordinary variables
1949 foreach ( $varnames as $var ) {
1950 if( isset( $GLOBALS[$var] ) ) {
1951 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
1952 $ins = str_replace( '{$' . $var . '}', $val, $ins );
1953 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
1954 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
1955 }
1956 }
1957
1958 // Table prefixes
1959 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
1960 array( &$this, 'tableNameCallback' ), $ins );
1961 return $ins;
1962 }
1963
1964 /**
1965 * Table name callback
1966 * @private
1967 */
1968 protected function tableNameCallback( $matches ) {
1969 return $this->tableName( $matches[1] );
1970 }
1971
1972 }
1973
1974 /**
1975 * Database abstraction object for mySQL
1976 * Inherit all methods and properties of Database::Database()
1977 *
1978 * @package MediaWiki
1979 * @see Database
1980 */
1981 class DatabaseMysql extends Database {
1982 # Inherit all
1983 }
1984
1985
1986 /**
1987 * Result wrapper for grabbing data queried by someone else
1988 *
1989 * @package MediaWiki
1990 */
1991 class ResultWrapper {
1992 var $db, $result;
1993
1994 /**
1995 * @todo document
1996 */
1997 function ResultWrapper( &$database, $result ) {
1998 $this->db =& $database;
1999 $this->result =& $result;
2000 }
2001
2002 /**
2003 * @todo document
2004 */
2005 function numRows() {
2006 return $this->db->numRows( $this->result );
2007 }
2008
2009 /**
2010 * @todo document
2011 */
2012 function fetchObject() {
2013 return $this->db->fetchObject( $this->result );
2014 }
2015
2016 /**
2017 * @todo document
2018 */
2019 function fetchRow() {
2020 return $this->db->fetchRow( $this->result );
2021 }
2022
2023 /**
2024 * @todo document
2025 */
2026 function free() {
2027 $this->db->freeResult( $this->result );
2028 unset( $this->result );
2029 unset( $this->db );
2030 }
2031
2032 function seek( $row ) {
2033 $this->db->dataSeek( $this->result, $row );
2034 }
2035
2036 }
2037
2038 ?>