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