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