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