Introducing 'frameless' keyword to [[Image:]] syntax which respects the user preferen...
[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 comment (you can use __METHOD__ or add some extra info)
682 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors... maybe best to catch the exception instead?
683 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure if $tempIgnore set
684 * @throws DBQueryError Thrown when the database returns an error of any kind
685 */
686 public function query( $sql, $fname = '', $tempIgnore = false ) {
687 global $wgProfiling;
688
689 if ( $wgProfiling ) {
690 # generalizeSQL will probably cut down the query to reasonable
691 # logging size most of the time. The substr is really just a sanity check.
692
693 # Who's been wasting my precious column space? -- TS
694 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
695
696 if ( is_null( $this->getLBInfo( 'master' ) ) ) {
697 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
698 $totalProf = 'Database::query';
699 } else {
700 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
701 $totalProf = 'Database::query-master';
702 }
703 wfProfileIn( $totalProf );
704 wfProfileIn( $queryProf );
705 }
706
707 $this->mLastQuery = $sql;
708
709 # Add a comment for easy SHOW PROCESSLIST interpretation
710 #if ( $fname ) {
711 global $wgUser;
712 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
713 $userName = $wgUser->getName();
714 if ( strlen( $userName ) > 15 ) {
715 $userName = substr( $userName, 0, 15 ) . '...';
716 }
717 $userName = str_replace( '/', '', $userName );
718 } else {
719 $userName = '';
720 }
721 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
722 #} else {
723 # $commentedSql = $sql;
724 #}
725
726 # If DBO_TRX is set, start a transaction
727 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
728 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
729 ) {
730 $this->begin();
731 }
732
733 if ( $this->debug() ) {
734 $sqlx = substr( $commentedSql, 0, 500 );
735 $sqlx = strtr( $sqlx, "\t\n", ' ' );
736 wfDebug( "SQL: $sqlx\n" );
737 }
738
739 # Do the query and handle errors
740 $ret = $this->doQuery( $commentedSql );
741
742 # Try reconnecting if the connection was lost
743 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
744 # Transaction is gone, like it or not
745 $this->mTrxLevel = 0;
746 wfDebug( "Connection lost, reconnecting...\n" );
747 if ( $this->ping() ) {
748 wfDebug( "Reconnected\n" );
749 $sqlx = substr( $commentedSql, 0, 500 );
750 $sqlx = strtr( $sqlx, "\t\n", ' ' );
751 global $wgRequestTime;
752 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
753 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
754 $ret = $this->doQuery( $commentedSql );
755 } else {
756 wfDebug( "Failed\n" );
757 }
758 }
759
760 if ( false === $ret ) {
761 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
762 }
763
764 if ( $wgProfiling ) {
765 wfProfileOut( $queryProf );
766 wfProfileOut( $totalProf );
767 }
768 return $ret;
769 }
770
771 /**
772 * The DBMS-dependent part of query()
773 * @param $sql String: SQL query.
774 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
775 * @access private
776 */
777 /*private*/ function doQuery( $sql ) {
778 if( $this->bufferResults() ) {
779 $ret = mysql_query( $sql, $this->mConn );
780 } else {
781 $ret = mysql_unbuffered_query( $sql, $this->mConn );
782 }
783 return $ret;
784 }
785
786 /**
787 * @param $error
788 * @param $errno
789 * @param $sql
790 * @param string $fname
791 * @param bool $tempIgnore
792 */
793 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
794 global $wgCommandLineMode;
795 # Ignore errors during error handling to avoid infinite recursion
796 $ignore = $this->ignoreErrors( true );
797 ++$this->mErrorCount;
798
799 if( $ignore || $tempIgnore ) {
800 wfDebug("SQL ERROR (ignored): $error\n");
801 $this->ignoreErrors( $ignore );
802 } else {
803 $sql1line = str_replace( "\n", "\\n", $sql );
804 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
805 wfDebug("SQL ERROR: " . $error . "\n");
806 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
807 }
808 }
809
810
811 /**
812 * Intended to be compatible with the PEAR::DB wrapper functions.
813 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
814 *
815 * ? = scalar value, quoted as necessary
816 * ! = raw SQL bit (a function for instance)
817 * & = filename; reads the file and inserts as a blob
818 * (we don't use this though...)
819 */
820 function prepare( $sql, $func = 'Database::prepare' ) {
821 /* MySQL doesn't support prepared statements (yet), so just
822 pack up the query for reference. We'll manually replace
823 the bits later. */
824 return array( 'query' => $sql, 'func' => $func );
825 }
826
827 function freePrepared( $prepared ) {
828 /* No-op for MySQL */
829 }
830
831 /**
832 * Execute a prepared query with the various arguments
833 * @param string $prepared the prepared sql
834 * @param mixed $args Either an array here, or put scalars as varargs
835 */
836 function execute( $prepared, $args = null ) {
837 if( !is_array( $args ) ) {
838 # Pull the var args
839 $args = func_get_args();
840 array_shift( $args );
841 }
842 $sql = $this->fillPrepared( $prepared['query'], $args );
843 return $this->query( $sql, $prepared['func'] );
844 }
845
846 /**
847 * Prepare & execute an SQL statement, quoting and inserting arguments
848 * in the appropriate places.
849 * @param string $query
850 * @param string $args ...
851 */
852 function safeQuery( $query, $args = null ) {
853 $prepared = $this->prepare( $query, 'Database::safeQuery' );
854 if( !is_array( $args ) ) {
855 # Pull the var args
856 $args = func_get_args();
857 array_shift( $args );
858 }
859 $retval = $this->execute( $prepared, $args );
860 $this->freePrepared( $prepared );
861 return $retval;
862 }
863
864 /**
865 * For faking prepared SQL statements on DBs that don't support
866 * it directly.
867 * @param string $preparedSql - a 'preparable' SQL statement
868 * @param array $args - array of arguments to fill it with
869 * @return string executable SQL
870 */
871 function fillPrepared( $preparedQuery, $args ) {
872 reset( $args );
873 $this->preparedArgs =& $args;
874 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
875 array( &$this, 'fillPreparedArg' ), $preparedQuery );
876 }
877
878 /**
879 * preg_callback func for fillPrepared()
880 * The arguments should be in $this->preparedArgs and must not be touched
881 * while we're doing this.
882 *
883 * @param array $matches
884 * @return string
885 * @private
886 */
887 function fillPreparedArg( $matches ) {
888 switch( $matches[1] ) {
889 case '\\?': return '?';
890 case '\\!': return '!';
891 case '\\&': return '&';
892 }
893 list( /* $n */ , $arg ) = each( $this->preparedArgs );
894 switch( $matches[1] ) {
895 case '?': return $this->addQuotes( $arg );
896 case '!': return $arg;
897 case '&':
898 # return $this->addQuotes( file_get_contents( $arg ) );
899 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
900 default:
901 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
902 }
903 }
904
905 /**#@+
906 * @param mixed $res A SQL result
907 */
908 /**
909 * Free a result object
910 */
911 function freeResult( $res ) {
912 if ( !@/**/mysql_free_result( $res ) ) {
913 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
914 }
915 }
916
917 /**
918 * Fetch the next row from the given result object, in object form.
919 * Fields can be retrieved with $row->fieldname, with fields acting like
920 * member variables.
921 *
922 * @param $res SQL result object as returned from Database::query(), etc.
923 * @return MySQL row object
924 * @throws DBUnexpectedError Thrown if the database returns an error
925 */
926 function fetchObject( $res ) {
927 @/**/$row = mysql_fetch_object( $res );
928 if( $this->lastErrno() ) {
929 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
930 }
931 return $row;
932 }
933
934 /**
935 * Fetch the next row from the given result object, in associative array
936 * form. Fields are retrieved with $row['fieldname'].
937 *
938 * @param $res SQL result object as returned from Database::query(), etc.
939 * @return MySQL row object
940 * @throws DBUnexpectedError Thrown if the database returns an error
941 */
942 function fetchRow( $res ) {
943 @/**/$row = mysql_fetch_array( $res );
944 if ( $this->lastErrno() ) {
945 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
946 }
947 return $row;
948 }
949
950 /**
951 * Get the number of rows in a result object
952 */
953 function numRows( $res ) {
954 @/**/$n = mysql_num_rows( $res );
955 if( $this->lastErrno() ) {
956 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
957 }
958 return $n;
959 }
960
961 /**
962 * Get the number of fields in a result object
963 * See documentation for mysql_num_fields()
964 */
965 function numFields( $res ) { return mysql_num_fields( $res ); }
966
967 /**
968 * Get a field name in a result object
969 * See documentation for mysql_field_name():
970 * http://www.php.net/mysql_field_name
971 */
972 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
973
974 /**
975 * Get the inserted value of an auto-increment row
976 *
977 * The value inserted should be fetched from nextSequenceValue()
978 *
979 * Example:
980 * $id = $dbw->nextSequenceValue('page_page_id_seq');
981 * $dbw->insert('page',array('page_id' => $id));
982 * $id = $dbw->insertId();
983 */
984 function insertId() { return mysql_insert_id( $this->mConn ); }
985
986 /**
987 * Change the position of the cursor in a result object
988 * See mysql_data_seek()
989 */
990 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
991
992 /**
993 * Get the last error number
994 * See mysql_errno()
995 */
996 function lastErrno() {
997 if ( $this->mConn ) {
998 return mysql_errno( $this->mConn );
999 } else {
1000 return mysql_errno();
1001 }
1002 }
1003
1004 /**
1005 * Get a description of the last error
1006 * See mysql_error() for more details
1007 */
1008 function lastError() {
1009 if ( $this->mConn ) {
1010 # Even if it's non-zero, it can still be invalid
1011 wfSuppressWarnings();
1012 $error = mysql_error( $this->mConn );
1013 if ( !$error ) {
1014 $error = mysql_error();
1015 }
1016 wfRestoreWarnings();
1017 } else {
1018 $error = mysql_error();
1019 }
1020 if( $error ) {
1021 $error .= ' (' . $this->mServer . ')';
1022 }
1023 return $error;
1024 }
1025 /**
1026 * Get the number of rows affected by the last write query
1027 * See mysql_affected_rows() for more details
1028 */
1029 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
1030 /**#@-*/ // end of template : @param $result
1031
1032 /**
1033 * Simple UPDATE wrapper
1034 * Usually aborts on failure
1035 * If errors are explicitly ignored, returns success
1036 *
1037 * This function exists for historical reasons, Database::update() has a more standard
1038 * calling convention and feature set
1039 */
1040 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
1041 {
1042 $table = $this->tableName( $table );
1043 $sql = "UPDATE $table SET $var = '" .
1044 $this->strencode( $value ) . "' WHERE ($cond)";
1045 return (bool)$this->query( $sql, $fname );
1046 }
1047
1048 /**
1049 * Simple SELECT wrapper, returns a single field, input must be encoded
1050 * Usually aborts on failure
1051 * If errors are explicitly ignored, returns FALSE on failure
1052 */
1053 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
1054 if ( !is_array( $options ) ) {
1055 $options = array( $options );
1056 }
1057 $options['LIMIT'] = 1;
1058
1059 $res = $this->select( $table, $var, $cond, $fname, $options );
1060 if ( $res === false || !$this->numRows( $res ) ) {
1061 return false;
1062 }
1063 $row = $this->fetchRow( $res );
1064 if ( $row !== false ) {
1065 $this->freeResult( $res );
1066 return $row[0];
1067 } else {
1068 return false;
1069 }
1070 }
1071
1072 /**
1073 * Returns an optional USE INDEX clause to go after the table, and a
1074 * string to go at the end of the query
1075 *
1076 * @private
1077 *
1078 * @param array $options an associative array of options to be turned into
1079 * an SQL query, valid keys are listed in the function.
1080 * @return array
1081 */
1082 function makeSelectOptions( $options ) {
1083 $preLimitTail = $postLimitTail = '';
1084 $startOpts = '';
1085
1086 $noKeyOptions = array();
1087 foreach ( $options as $key => $option ) {
1088 if ( is_numeric( $key ) ) {
1089 $noKeyOptions[$option] = true;
1090 }
1091 }
1092
1093 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
1094 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1095 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
1096
1097 //if (isset($options['LIMIT'])) {
1098 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1099 // isset($options['OFFSET']) ? $options['OFFSET']
1100 // : false);
1101 //}
1102
1103 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1104 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1105 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1106
1107 # Various MySQL extensions
1108 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
1109 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
1110 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
1111 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
1112 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
1113 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
1114 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
1115 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
1116
1117 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1118 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1119 } else {
1120 $useIndex = '';
1121 }
1122
1123 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1124 }
1125
1126 /**
1127 * SELECT wrapper
1128 *
1129 * @param mixed $table Array or string, table name(s) (prefix auto-added)
1130 * @param mixed $vars Array or string, field name(s) to be retrieved
1131 * @param mixed $conds Array or string, condition(s) for WHERE
1132 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1133 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1134 * see Database::makeSelectOptions code for list of supported stuff
1135 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
1136 */
1137 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
1138 {
1139 if( is_array( $vars ) ) {
1140 $vars = implode( ',', $vars );
1141 }
1142 if( !is_array( $options ) ) {
1143 $options = array( $options );
1144 }
1145 if( is_array( $table ) ) {
1146 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1147 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
1148 else
1149 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1150 } elseif ($table!='') {
1151 if ($table{0}==' ') {
1152 $from = ' FROM ' . $table;
1153 } else {
1154 $from = ' FROM ' . $this->tableName( $table );
1155 }
1156 } else {
1157 $from = '';
1158 }
1159
1160 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1161
1162 if( !empty( $conds ) ) {
1163 if ( is_array( $conds ) ) {
1164 $conds = $this->makeList( $conds, LIST_AND );
1165 }
1166 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1167 } else {
1168 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1169 }
1170
1171 if (isset($options['LIMIT']))
1172 $sql = $this->limitResult($sql, $options['LIMIT'],
1173 isset($options['OFFSET']) ? $options['OFFSET'] : false);
1174 $sql = "$sql $postLimitTail";
1175
1176 if (isset($options['EXPLAIN'])) {
1177 $sql = 'EXPLAIN ' . $sql;
1178 }
1179 return $this->query( $sql, $fname );
1180 }
1181
1182 /**
1183 * Single row SELECT wrapper
1184 * Aborts or returns FALSE on error
1185 *
1186 * $vars: the selected variables
1187 * $conds: a condition map, terms are ANDed together.
1188 * Items with numeric keys are taken to be literal conditions
1189 * Takes an array of selected variables, and a condition map, which is ANDed
1190 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1191 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1192 * $obj- >page_id is the ID of the Astronomy article
1193 *
1194 * @todo migrate documentation to phpdocumentor format
1195 */
1196 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
1197 $options['LIMIT'] = 1;
1198 $res = $this->select( $table, $vars, $conds, $fname, $options );
1199 if ( $res === false )
1200 return false;
1201 if ( !$this->numRows($res) ) {
1202 $this->freeResult($res);
1203 return false;
1204 }
1205 $obj = $this->fetchObject( $res );
1206 $this->freeResult( $res );
1207 return $obj;
1208
1209 }
1210
1211 /**
1212 * Estimate rows in dataset
1213 * Returns estimated count, based on EXPLAIN output
1214 * Takes same arguments as Database::select()
1215 */
1216
1217 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1218 $options['EXPLAIN']=true;
1219 $res = $this->select ($table, $vars, $conds, $fname, $options );
1220 if ( $res === false )
1221 return false;
1222 if (!$this->numRows($res)) {
1223 $this->freeResult($res);
1224 return 0;
1225 }
1226
1227 $rows=1;
1228
1229 while( $plan = $this->fetchObject( $res ) ) {
1230 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
1231 }
1232
1233 $this->freeResult($res);
1234 return $rows;
1235 }
1236
1237
1238 /**
1239 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1240 * It's only slightly flawed. Don't use for anything important.
1241 *
1242 * @param string $sql A SQL Query
1243 * @static
1244 */
1245 static function generalizeSQL( $sql ) {
1246 # This does the same as the regexp below would do, but in such a way
1247 # as to avoid crashing php on some large strings.
1248 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1249
1250 $sql = str_replace ( "\\\\", '', $sql);
1251 $sql = str_replace ( "\\'", '', $sql);
1252 $sql = str_replace ( "\\\"", '', $sql);
1253 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1254 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1255
1256 # All newlines, tabs, etc replaced by single space
1257 $sql = preg_replace ( '/\s+/', ' ', $sql);
1258
1259 # All numbers => N
1260 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1261
1262 return $sql;
1263 }
1264
1265 /**
1266 * Determines whether a field exists in a table
1267 * Usually aborts on failure
1268 * If errors are explicitly ignored, returns NULL on failure
1269 */
1270 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1271 $table = $this->tableName( $table );
1272 $res = $this->query( 'DESCRIBE '.$table, $fname );
1273 if ( !$res ) {
1274 return NULL;
1275 }
1276
1277 $found = false;
1278
1279 while ( $row = $this->fetchObject( $res ) ) {
1280 if ( $row->Field == $field ) {
1281 $found = true;
1282 break;
1283 }
1284 }
1285 return $found;
1286 }
1287
1288 /**
1289 * Determines whether an index exists
1290 * Usually aborts on failure
1291 * If errors are explicitly ignored, returns NULL on failure
1292 */
1293 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1294 $info = $this->indexInfo( $table, $index, $fname );
1295 if ( is_null( $info ) ) {
1296 return NULL;
1297 } else {
1298 return $info !== false;
1299 }
1300 }
1301
1302
1303 /**
1304 * Get information about an index into an object
1305 * Returns false if the index does not exist
1306 */
1307 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1308 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1309 # SHOW INDEX should work for 3.x and up:
1310 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1311 $table = $this->tableName( $table );
1312 $sql = 'SHOW INDEX FROM '.$table;
1313 $res = $this->query( $sql, $fname );
1314 if ( !$res ) {
1315 return NULL;
1316 }
1317
1318 $result = array();
1319 while ( $row = $this->fetchObject( $res ) ) {
1320 if ( $row->Key_name == $index ) {
1321 $result[] = $row;
1322 }
1323 }
1324 $this->freeResult($res);
1325
1326 return empty($result) ? false : $result;
1327 }
1328
1329 /**
1330 * Query whether a given table exists
1331 */
1332 function tableExists( $table ) {
1333 $table = $this->tableName( $table );
1334 $old = $this->ignoreErrors( true );
1335 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1336 $this->ignoreErrors( $old );
1337 if( $res ) {
1338 $this->freeResult( $res );
1339 return true;
1340 } else {
1341 return false;
1342 }
1343 }
1344
1345 /**
1346 * mysql_fetch_field() wrapper
1347 * Returns false if the field doesn't exist
1348 *
1349 * @param $table
1350 * @param $field
1351 */
1352 function fieldInfo( $table, $field ) {
1353 $table = $this->tableName( $table );
1354 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1355 $n = mysql_num_fields( $res );
1356 for( $i = 0; $i < $n; $i++ ) {
1357 $meta = mysql_fetch_field( $res, $i );
1358 if( $field == $meta->name ) {
1359 return new MySQLField($meta);
1360 }
1361 }
1362 return false;
1363 }
1364
1365 /**
1366 * mysql_field_type() wrapper
1367 */
1368 function fieldType( $res, $index ) {
1369 return mysql_field_type( $res, $index );
1370 }
1371
1372 /**
1373 * Determines if a given index is unique
1374 */
1375 function indexUnique( $table, $index ) {
1376 $indexInfo = $this->indexInfo( $table, $index );
1377 if ( !$indexInfo ) {
1378 return NULL;
1379 }
1380 return !$indexInfo[0]->Non_unique;
1381 }
1382
1383 /**
1384 * INSERT wrapper, inserts an array into a table
1385 *
1386 * $a may be a single associative array, or an array of these with numeric keys, for
1387 * multi-row insert.
1388 *
1389 * Usually aborts on failure
1390 * If errors are explicitly ignored, returns success
1391 */
1392 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1393 # No rows to insert, easy just return now
1394 if ( !count( $a ) ) {
1395 return true;
1396 }
1397
1398 $table = $this->tableName( $table );
1399 if ( !is_array( $options ) ) {
1400 $options = array( $options );
1401 }
1402 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1403 $multi = true;
1404 $keys = array_keys( $a[0] );
1405 } else {
1406 $multi = false;
1407 $keys = array_keys( $a );
1408 }
1409
1410 $sql = 'INSERT ' . implode( ' ', $options ) .
1411 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1412
1413 if ( $multi ) {
1414 $first = true;
1415 foreach ( $a as $row ) {
1416 if ( $first ) {
1417 $first = false;
1418 } else {
1419 $sql .= ',';
1420 }
1421 $sql .= '(' . $this->makeList( $row ) . ')';
1422 }
1423 } else {
1424 $sql .= '(' . $this->makeList( $a ) . ')';
1425 }
1426 return (bool)$this->query( $sql, $fname );
1427 }
1428
1429 /**
1430 * Make UPDATE options for the Database::update function
1431 *
1432 * @private
1433 * @param array $options The options passed to Database::update
1434 * @return string
1435 */
1436 function makeUpdateOptions( $options ) {
1437 if( !is_array( $options ) ) {
1438 $options = array( $options );
1439 }
1440 $opts = array();
1441 if ( in_array( 'LOW_PRIORITY', $options ) )
1442 $opts[] = $this->lowPriorityOption();
1443 if ( in_array( 'IGNORE', $options ) )
1444 $opts[] = 'IGNORE';
1445 return implode(' ', $opts);
1446 }
1447
1448 /**
1449 * UPDATE wrapper, takes a condition array and a SET array
1450 *
1451 * @param string $table The table to UPDATE
1452 * @param array $values An array of values to SET
1453 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1454 * @param string $fname The Class::Function calling this function
1455 * (for the log)
1456 * @param array $options An array of UPDATE options, can be one or
1457 * more of IGNORE, LOW_PRIORITY
1458 */
1459 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1460 $table = $this->tableName( $table );
1461 $opts = $this->makeUpdateOptions( $options );
1462 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1463 if ( $conds != '*' ) {
1464 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1465 }
1466 $this->query( $sql, $fname );
1467 }
1468
1469 /**
1470 * Makes an encoded list of strings from an array
1471 * $mode:
1472 * LIST_COMMA - comma separated, no field names
1473 * LIST_AND - ANDed WHERE clause (without the WHERE)
1474 * LIST_OR - ORed WHERE clause (without the WHERE)
1475 * LIST_SET - comma separated with field names, like a SET clause
1476 * LIST_NAMES - comma separated field names
1477 */
1478 function makeList( $a, $mode = LIST_COMMA ) {
1479 if ( !is_array( $a ) ) {
1480 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1481 }
1482
1483 $first = true;
1484 $list = '';
1485 foreach ( $a as $field => $value ) {
1486 if ( !$first ) {
1487 if ( $mode == LIST_AND ) {
1488 $list .= ' AND ';
1489 } elseif($mode == LIST_OR) {
1490 $list .= ' OR ';
1491 } else {
1492 $list .= ',';
1493 }
1494 } else {
1495 $first = false;
1496 }
1497 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1498 $list .= "($value)";
1499 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1500 $list .= "$value";
1501 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array ($value) ) {
1502 $list .= $field." IN (".$this->makeList($value).") ";
1503 } else {
1504 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1505 $list .= "$field = ";
1506 }
1507 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1508 }
1509 }
1510 return $list;
1511 }
1512
1513 /**
1514 * Change the current database
1515 */
1516 function selectDB( $db ) {
1517 $this->mDBname = $db;
1518 return mysql_select_db( $db, $this->mConn );
1519 }
1520
1521 /**
1522 * Format a table name ready for use in constructing an SQL query
1523 *
1524 * This does two important things: it quotes table names which as necessary,
1525 * and it adds a table prefix if there is one.
1526 *
1527 * All functions of this object which require a table name call this function
1528 * themselves. Pass the canonical name to such functions. This is only needed
1529 * when calling query() directly.
1530 *
1531 * @param string $name database table name
1532 */
1533 function tableName( $name ) {
1534 global $wgSharedDB;
1535 # Skip quoted literals
1536 if ( $name{0} != '`' ) {
1537 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1538 $name = "{$this->mTablePrefix}$name";
1539 }
1540 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1541 $name = "`$wgSharedDB`.`$name`";
1542 } else {
1543 # Standard quoting
1544 $name = "`$name`";
1545 }
1546 }
1547 return $name;
1548 }
1549
1550 /**
1551 * Fetch a number of table names into an array
1552 * This is handy when you need to construct SQL for joins
1553 *
1554 * Example:
1555 * extract($dbr->tableNames('user','watchlist'));
1556 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1557 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1558 */
1559 public function tableNames() {
1560 $inArray = func_get_args();
1561 $retVal = array();
1562 foreach ( $inArray as $name ) {
1563 $retVal[$name] = $this->tableName( $name );
1564 }
1565 return $retVal;
1566 }
1567
1568 /**
1569 * Fetch a number of table names into an zero-indexed numerical array
1570 * This is handy when you need to construct SQL for joins
1571 *
1572 * Example:
1573 * list( $user, $watchlist ) = $dbr->tableNames('user','watchlist');
1574 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1575 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1576 */
1577 public function tableNamesN() {
1578 $inArray = func_get_args();
1579 $retVal = array();
1580 foreach ( $inArray as $name ) {
1581 $retVal[] = $this->tableName( $name );
1582 }
1583 return $retVal;
1584 }
1585
1586 /**
1587 * @private
1588 */
1589 function tableNamesWithUseIndex( $tables, $use_index ) {
1590 $ret = array();
1591
1592 foreach ( $tables as $table )
1593 if ( @$use_index[$table] !== null )
1594 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1595 else
1596 $ret[] = $this->tableName( $table );
1597
1598 return implode( ',', $ret );
1599 }
1600
1601 /**
1602 * Wrapper for addslashes()
1603 * @param string $s String to be slashed.
1604 * @return string slashed string.
1605 */
1606 function strencode( $s ) {
1607 return mysql_real_escape_string( $s, $this->mConn );
1608 }
1609
1610 /**
1611 * If it's a string, adds quotes and backslashes
1612 * Otherwise returns as-is
1613 */
1614 function addQuotes( $s ) {
1615 if ( is_null( $s ) ) {
1616 return 'NULL';
1617 } else {
1618 # This will also quote numeric values. This should be harmless,
1619 # and protects against weird problems that occur when they really
1620 # _are_ strings such as article titles and string->number->string
1621 # conversion is not 1:1.
1622 return "'" . $this->strencode( $s ) . "'";
1623 }
1624 }
1625
1626 /**
1627 * Escape string for safe LIKE usage
1628 */
1629 function escapeLike( $s ) {
1630 $s=$this->strencode( $s );
1631 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1632 return $s;
1633 }
1634
1635 /**
1636 * Returns an appropriately quoted sequence value for inserting a new row.
1637 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1638 * subclass will return an integer, and save the value for insertId()
1639 */
1640 function nextSequenceValue( $seqName ) {
1641 return NULL;
1642 }
1643
1644 /**
1645 * USE INDEX clause
1646 * PostgreSQL doesn't have them and returns ""
1647 */
1648 function useIndexClause( $index ) {
1649 return "FORCE INDEX ($index)";
1650 }
1651
1652 /**
1653 * REPLACE query wrapper
1654 * PostgreSQL simulates this with a DELETE followed by INSERT
1655 * $row is the row to insert, an associative array
1656 * $uniqueIndexes is an array of indexes. Each element may be either a
1657 * field name or an array of field names
1658 *
1659 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1660 * However if you do this, you run the risk of encountering errors which wouldn't have
1661 * occurred in MySQL
1662 *
1663 * @todo migrate comment to phodocumentor format
1664 */
1665 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1666 $table = $this->tableName( $table );
1667
1668 # Single row case
1669 if ( !is_array( reset( $rows ) ) ) {
1670 $rows = array( $rows );
1671 }
1672
1673 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1674 $first = true;
1675 foreach ( $rows as $row ) {
1676 if ( $first ) {
1677 $first = false;
1678 } else {
1679 $sql .= ',';
1680 }
1681 $sql .= '(' . $this->makeList( $row ) . ')';
1682 }
1683 return $this->query( $sql, $fname );
1684 }
1685
1686 /**
1687 * DELETE where the condition is a join
1688 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1689 *
1690 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1691 * join condition matches, set $conds='*'
1692 *
1693 * DO NOT put the join condition in $conds
1694 *
1695 * @param string $delTable The table to delete from.
1696 * @param string $joinTable The other table.
1697 * @param string $delVar The variable to join on, in the first table.
1698 * @param string $joinVar The variable to join on, in the second table.
1699 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1700 */
1701 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1702 if ( !$conds ) {
1703 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1704 }
1705
1706 $delTable = $this->tableName( $delTable );
1707 $joinTable = $this->tableName( $joinTable );
1708 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1709 if ( $conds != '*' ) {
1710 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1711 }
1712
1713 return $this->query( $sql, $fname );
1714 }
1715
1716 /**
1717 * Returns the size of a text field, or -1 for "unlimited"
1718 */
1719 function textFieldSize( $table, $field ) {
1720 $table = $this->tableName( $table );
1721 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1722 $res = $this->query( $sql, 'Database::textFieldSize' );
1723 $row = $this->fetchObject( $res );
1724 $this->freeResult( $res );
1725
1726 $m = array();
1727 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1728 $size = $m[1];
1729 } else {
1730 $size = -1;
1731 }
1732 return $size;
1733 }
1734
1735 /**
1736 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1737 */
1738 function lowPriorityOption() {
1739 return 'LOW_PRIORITY';
1740 }
1741
1742 /**
1743 * DELETE query wrapper
1744 *
1745 * Use $conds == "*" to delete all rows
1746 */
1747 function delete( $table, $conds, $fname = 'Database::delete' ) {
1748 if ( !$conds ) {
1749 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1750 }
1751 $table = $this->tableName( $table );
1752 $sql = "DELETE FROM $table";
1753 if ( $conds != '*' ) {
1754 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1755 }
1756 return $this->query( $sql, $fname );
1757 }
1758
1759 /**
1760 * INSERT SELECT wrapper
1761 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1762 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1763 * $conds may be "*" to copy the whole table
1764 * srcTable may be an array of tables.
1765 */
1766 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1767 $insertOptions = array(), $selectOptions = array() )
1768 {
1769 $destTable = $this->tableName( $destTable );
1770 if ( is_array( $insertOptions ) ) {
1771 $insertOptions = implode( ' ', $insertOptions );
1772 }
1773 if( !is_array( $selectOptions ) ) {
1774 $selectOptions = array( $selectOptions );
1775 }
1776 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1777 if( is_array( $srcTable ) ) {
1778 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1779 } else {
1780 $srcTable = $this->tableName( $srcTable );
1781 }
1782 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1783 " SELECT $startOpts " . implode( ',', $varMap ) .
1784 " FROM $srcTable $useIndex ";
1785 if ( $conds != '*' ) {
1786 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1787 }
1788 $sql .= " $tailOpts";
1789 return $this->query( $sql, $fname );
1790 }
1791
1792 /**
1793 * Construct a LIMIT query with optional offset
1794 * This is used for query pages
1795 * $sql string SQL query we will append the limit too
1796 * $limit integer the SQL limit
1797 * $offset integer the SQL offset (default false)
1798 */
1799 function limitResult($sql, $limit, $offset=false) {
1800 if( !is_numeric($limit) ) {
1801 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1802 }
1803 return " $sql LIMIT "
1804 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1805 . "{$limit} ";
1806 }
1807 function limitResultForUpdate($sql, $num) {
1808 return $this->limitResult($sql, $num, 0);
1809 }
1810
1811 /**
1812 * Returns an SQL expression for a simple conditional.
1813 * Uses IF on MySQL.
1814 *
1815 * @param string $cond SQL expression which will result in a boolean value
1816 * @param string $trueVal SQL expression to return if true
1817 * @param string $falseVal SQL expression to return if false
1818 * @return string SQL fragment
1819 */
1820 function conditional( $cond, $trueVal, $falseVal ) {
1821 return " IF($cond, $trueVal, $falseVal) ";
1822 }
1823
1824 /**
1825 * Determines if the last failure was due to a deadlock
1826 */
1827 function wasDeadlock() {
1828 return $this->lastErrno() == 1213;
1829 }
1830
1831 /**
1832 * Perform a deadlock-prone transaction.
1833 *
1834 * This function invokes a callback function to perform a set of write
1835 * queries. If a deadlock occurs during the processing, the transaction
1836 * will be rolled back and the callback function will be called again.
1837 *
1838 * Usage:
1839 * $dbw->deadlockLoop( callback, ... );
1840 *
1841 * Extra arguments are passed through to the specified callback function.
1842 *
1843 * Returns whatever the callback function returned on its successful,
1844 * iteration, or false on error, for example if the retry limit was
1845 * reached.
1846 */
1847 function deadlockLoop() {
1848 $myFname = 'Database::deadlockLoop';
1849
1850 $this->begin();
1851 $args = func_get_args();
1852 $function = array_shift( $args );
1853 $oldIgnore = $this->ignoreErrors( true );
1854 $tries = DEADLOCK_TRIES;
1855 if ( is_array( $function ) ) {
1856 $fname = $function[0];
1857 } else {
1858 $fname = $function;
1859 }
1860 do {
1861 $retVal = call_user_func_array( $function, $args );
1862 $error = $this->lastError();
1863 $errno = $this->lastErrno();
1864 $sql = $this->lastQuery();
1865
1866 if ( $errno ) {
1867 if ( $this->wasDeadlock() ) {
1868 # Retry
1869 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1870 } else {
1871 $this->reportQueryError( $error, $errno, $sql, $fname );
1872 }
1873 }
1874 } while( $this->wasDeadlock() && --$tries > 0 );
1875 $this->ignoreErrors( $oldIgnore );
1876 if ( $tries <= 0 ) {
1877 $this->query( 'ROLLBACK', $myFname );
1878 $this->reportQueryError( $error, $errno, $sql, $fname );
1879 return false;
1880 } else {
1881 $this->query( 'COMMIT', $myFname );
1882 return $retVal;
1883 }
1884 }
1885
1886 /**
1887 * Do a SELECT MASTER_POS_WAIT()
1888 *
1889 * @param string $file the binlog file
1890 * @param string $pos the binlog position
1891 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1892 */
1893 function masterPosWait( $file, $pos, $timeout ) {
1894 $fname = 'Database::masterPosWait';
1895 wfProfileIn( $fname );
1896
1897
1898 # Commit any open transactions
1899 $this->immediateCommit();
1900
1901 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1902 $encFile = $this->strencode( $file );
1903 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1904 $res = $this->doQuery( $sql );
1905 if ( $res && $row = $this->fetchRow( $res ) ) {
1906 $this->freeResult( $res );
1907 wfProfileOut( $fname );
1908 return $row[0];
1909 } else {
1910 wfProfileOut( $fname );
1911 return false;
1912 }
1913 }
1914
1915 /**
1916 * Get the position of the master from SHOW SLAVE STATUS
1917 */
1918 function getSlavePos() {
1919 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1920 $row = $this->fetchObject( $res );
1921 if ( $row ) {
1922 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1923 } else {
1924 return array( false, false );
1925 }
1926 }
1927
1928 /**
1929 * Get the position of the master from SHOW MASTER STATUS
1930 */
1931 function getMasterPos() {
1932 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1933 $row = $this->fetchObject( $res );
1934 if ( $row ) {
1935 return array( $row->File, $row->Position );
1936 } else {
1937 return array( false, false );
1938 }
1939 }
1940
1941 /**
1942 * Begin a transaction, committing any previously open transaction
1943 */
1944 function begin( $fname = 'Database::begin' ) {
1945 $this->query( 'BEGIN', $fname );
1946 $this->mTrxLevel = 1;
1947 }
1948
1949 /**
1950 * End a transaction
1951 */
1952 function commit( $fname = 'Database::commit' ) {
1953 $this->query( 'COMMIT', $fname );
1954 $this->mTrxLevel = 0;
1955 }
1956
1957 /**
1958 * Rollback a transaction
1959 */
1960 function rollback( $fname = 'Database::rollback' ) {
1961 $this->query( 'ROLLBACK', $fname );
1962 $this->mTrxLevel = 0;
1963 }
1964
1965 /**
1966 * Begin a transaction, committing any previously open transaction
1967 * @deprecated use begin()
1968 */
1969 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1970 $this->begin();
1971 }
1972
1973 /**
1974 * Commit transaction, if one is open
1975 * @deprecated use commit()
1976 */
1977 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1978 $this->commit();
1979 }
1980
1981 /**
1982 * Return MW-style timestamp used for MySQL schema
1983 */
1984 function timestamp( $ts=0 ) {
1985 return wfTimestamp(TS_MW,$ts);
1986 }
1987
1988 /**
1989 * Local database timestamp format or null
1990 */
1991 function timestampOrNull( $ts = null ) {
1992 if( is_null( $ts ) ) {
1993 return null;
1994 } else {
1995 return $this->timestamp( $ts );
1996 }
1997 }
1998
1999 /**
2000 * @todo document
2001 */
2002 function resultObject( $result ) {
2003 if( empty( $result ) ) {
2004 return NULL;
2005 } else {
2006 return new ResultWrapper( $this, $result );
2007 }
2008 }
2009
2010 /**
2011 * Return aggregated value alias
2012 */
2013 function aggregateValue ($valuedata,$valuename='value') {
2014 return $valuename;
2015 }
2016
2017 /**
2018 * @return string wikitext of a link to the server software's web site
2019 */
2020 function getSoftwareLink() {
2021 return "[http://www.mysql.com/ MySQL]";
2022 }
2023
2024 /**
2025 * @return string Version information from the database
2026 */
2027 function getServerVersion() {
2028 return mysql_get_server_info( $this->mConn );
2029 }
2030
2031 /**
2032 * Ping the server and try to reconnect if it there is no connection
2033 */
2034 function ping() {
2035 if( function_exists( 'mysql_ping' ) ) {
2036 return mysql_ping( $this->mConn );
2037 } else {
2038 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2039 return true;
2040 }
2041 }
2042
2043 /**
2044 * Get slave lag.
2045 * At the moment, this will only work if the DB user has the PROCESS privilege
2046 */
2047 function getLag() {
2048 $res = $this->query( 'SHOW PROCESSLIST' );
2049 # Find slave SQL thread. Assumed to be the second one running, which is a bit
2050 # dubious, but unfortunately there's no easy rigorous way
2051 while ( $row = $this->fetchObject( $res ) ) {
2052 /* This should work for most situations - when default db
2053 * for thread is not specified, it had no events executed,
2054 * and therefore it doesn't know yet how lagged it is.
2055 *
2056 * Relay log I/O thread does not select databases.
2057 */
2058 if ( $row->User == 'system user' &&
2059 $row->State != 'Waiting for master to send event' &&
2060 $row->State != 'Connecting to master' &&
2061 $row->State != 'Queueing master event to the relay log' &&
2062 $row->State != 'Waiting for master update' &&
2063 $row->State != 'Requesting binlog dump'
2064 ) {
2065 # This is it, return the time (except -ve)
2066 if ( $row->Time > 0x7fffffff ) {
2067 return false;
2068 } else {
2069 return $row->Time;
2070 }
2071 }
2072 }
2073 return false;
2074 }
2075
2076 /**
2077 * Get status information from SHOW STATUS in an associative array
2078 */
2079 function getStatus($which="%") {
2080 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2081 $status = array();
2082 while ( $row = $this->fetchObject( $res ) ) {
2083 $status[$row->Variable_name] = $row->Value;
2084 }
2085 return $status;
2086 }
2087
2088 /**
2089 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2090 */
2091 function maxListLen() {
2092 return 0;
2093 }
2094
2095 function encodeBlob($b) {
2096 return $b;
2097 }
2098
2099 function decodeBlob($b) {
2100 return $b;
2101 }
2102
2103 /**
2104 * Override database's default connection timeout.
2105 * May be useful for very long batch queries such as
2106 * full-wiki dumps, where a single query reads out
2107 * over hours or days.
2108 * @param int $timeout in seconds
2109 */
2110 public function setTimeout( $timeout ) {
2111 $this->query( "SET net_read_timeout=$timeout" );
2112 $this->query( "SET net_write_timeout=$timeout" );
2113 }
2114
2115 /**
2116 * Read and execute SQL commands from a file.
2117 * Returns true on success, error string on failure
2118 * @param string $filename File name to open
2119 * @param callback $lineCallback Optional function called before reading each line
2120 * @param callback $resultCallback Optional function called for each MySQL result
2121 */
2122 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2123 $fp = fopen( $filename, 'r' );
2124 if ( false === $fp ) {
2125 return "Could not open \"{$filename}\".\n";
2126 }
2127 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2128 fclose( $fp );
2129 return $error;
2130 }
2131
2132 /**
2133 * Read and execute commands from an open file handle
2134 * Returns true on success, error string on failure
2135 * @param string $fp File handle
2136 * @param callback $lineCallback Optional function called before reading each line
2137 * @param callback $resultCallback Optional function called for each MySQL result
2138 */
2139 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2140 $cmd = "";
2141 $done = false;
2142 $dollarquote = false;
2143
2144 while ( ! feof( $fp ) ) {
2145 if ( $lineCallback ) {
2146 call_user_func( $lineCallback );
2147 }
2148 $line = trim( fgets( $fp, 1024 ) );
2149 $sl = strlen( $line ) - 1;
2150
2151 if ( $sl < 0 ) { continue; }
2152 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2153
2154 ## Allow dollar quoting for function declarations
2155 if (substr($line,0,4) == '$mw$') {
2156 if ($dollarquote) {
2157 $dollarquote = false;
2158 $done = true;
2159 }
2160 else {
2161 $dollarquote = true;
2162 }
2163 }
2164 else if (!$dollarquote) {
2165 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2166 $done = true;
2167 $line = substr( $line, 0, $sl );
2168 }
2169 }
2170
2171 if ( '' != $cmd ) { $cmd .= ' '; }
2172 $cmd .= "$line\n";
2173
2174 if ( $done ) {
2175 $cmd = str_replace(';;', ";", $cmd);
2176 $cmd = $this->replaceVars( $cmd );
2177 $res = $this->query( $cmd, __METHOD__, true );
2178 if ( $resultCallback ) {
2179 call_user_func( $resultCallback, $this->resultObject( $res ) );
2180 }
2181
2182 if ( false === $res ) {
2183 $err = $this->lastError();
2184 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2185 }
2186
2187 $cmd = '';
2188 $done = false;
2189 }
2190 }
2191 return true;
2192 }
2193
2194
2195 /**
2196 * Replace variables in sourced SQL
2197 */
2198 protected function replaceVars( $ins ) {
2199 $varnames = array(
2200 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2201 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2202 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2203 );
2204
2205 // Ordinary variables
2206 foreach ( $varnames as $var ) {
2207 if( isset( $GLOBALS[$var] ) ) {
2208 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2209 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2210 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2211 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2212 }
2213 }
2214
2215 // Table prefixes
2216 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2217 array( &$this, 'tableNameCallback' ), $ins );
2218 return $ins;
2219 }
2220
2221 /**
2222 * Table name callback
2223 * @private
2224 */
2225 protected function tableNameCallback( $matches ) {
2226 return $this->tableName( $matches[1] );
2227 }
2228
2229 }
2230
2231 /**
2232 * Database abstraction object for mySQL
2233 * Inherit all methods and properties of Database::Database()
2234 *
2235 * @addtogroup Database
2236 * @see Database
2237 */
2238 class DatabaseMysql extends Database {
2239 # Inherit all
2240 }
2241
2242
2243 /**
2244 * Result wrapper for grabbing data queried by someone else
2245 * @addtogroup Database
2246 */
2247 class ResultWrapper {
2248 var $db, $result;
2249
2250 /**
2251 * @todo document
2252 */
2253 function ResultWrapper( &$database, $result ) {
2254 $this->db =& $database;
2255 $this->result =& $result;
2256 }
2257
2258 /**
2259 * @todo document
2260 */
2261 function numRows() {
2262 return $this->db->numRows( $this->result );
2263 }
2264
2265 /**
2266 * @todo document
2267 */
2268 function fetchObject() {
2269 return $this->db->fetchObject( $this->result );
2270 }
2271
2272 /**
2273 * @todo document
2274 */
2275 function fetchRow() {
2276 return $this->db->fetchRow( $this->result );
2277 }
2278
2279 /**
2280 * @todo document
2281 */
2282 function free() {
2283 $this->db->freeResult( $this->result );
2284 unset( $this->result );
2285 unset( $this->db );
2286 }
2287
2288 function seek( $row ) {
2289 $this->db->dataSeek( $this->result, $row );
2290 }
2291
2292 function rewind() {
2293 if ($this->numRows()) {
2294 $this->db->dataSeek($this->result, 0);
2295 }
2296 }
2297
2298 }
2299
2300 ?>