APIEDIT BRANCH MERGE:
[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 $list .= $field." IN (".$this->makeList($value).") ";
1568 } elseif( is_null($value) ) {
1569 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1570 $list .= "$field IS ";
1571 } elseif ( $mode == LIST_SET ) {
1572 $list .= "$field = ";
1573 }
1574 $list .= 'NULL';
1575 } else {
1576 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1577 $list .= "$field = ";
1578 }
1579 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1580 }
1581 }
1582 return $list;
1583 }
1584
1585 /**
1586 * Change the current database
1587 */
1588 function selectDB( $db ) {
1589 $this->mDBname = $db;
1590 return mysql_select_db( $db, $this->mConn );
1591 }
1592
1593 /**
1594 * Format a table name ready for use in constructing an SQL query
1595 *
1596 * This does two important things: it quotes table names which as necessary,
1597 * and it adds a table prefix if there is one.
1598 *
1599 * All functions of this object which require a table name call this function
1600 * themselves. Pass the canonical name to such functions. This is only needed
1601 * when calling query() directly.
1602 *
1603 * @param string $name database table name
1604 */
1605 function tableName( $name ) {
1606 global $wgSharedDB;
1607 # Skip quoted literals
1608 if ( $name{0} != '`' ) {
1609 if ( $this->mTablePrefix !== '' && strpos( $name, '.' ) === false ) {
1610 $name = "{$this->mTablePrefix}$name";
1611 }
1612 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1613 $name = "`$wgSharedDB`.`$name`";
1614 } else {
1615 # Standard quoting
1616 $name = "`$name`";
1617 }
1618 }
1619 return $name;
1620 }
1621
1622 /**
1623 * Fetch a number of table names into an array
1624 * This is handy when you need to construct SQL for joins
1625 *
1626 * Example:
1627 * extract($dbr->tableNames('user','watchlist'));
1628 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1629 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1630 */
1631 public function tableNames() {
1632 $inArray = func_get_args();
1633 $retVal = array();
1634 foreach ( $inArray as $name ) {
1635 $retVal[$name] = $this->tableName( $name );
1636 }
1637 return $retVal;
1638 }
1639
1640 /**
1641 * Fetch a number of table names into an zero-indexed numerical array
1642 * This is handy when you need to construct SQL for joins
1643 *
1644 * Example:
1645 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1646 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1647 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1648 */
1649 public function tableNamesN() {
1650 $inArray = func_get_args();
1651 $retVal = array();
1652 foreach ( $inArray as $name ) {
1653 $retVal[] = $this->tableName( $name );
1654 }
1655 return $retVal;
1656 }
1657
1658 /**
1659 * @private
1660 */
1661 function tableNamesWithUseIndex( $tables, $use_index ) {
1662 $ret = array();
1663
1664 foreach ( $tables as $table )
1665 if ( @$use_index[$table] !== null )
1666 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1667 else
1668 $ret[] = $this->tableName( $table );
1669
1670 return implode( ',', $ret );
1671 }
1672
1673 /**
1674 * Wrapper for addslashes()
1675 * @param string $s String to be slashed.
1676 * @return string slashed string.
1677 */
1678 function strencode( $s ) {
1679 return mysql_real_escape_string( $s, $this->mConn );
1680 }
1681
1682 /**
1683 * If it's a string, adds quotes and backslashes
1684 * Otherwise returns as-is
1685 */
1686 function addQuotes( $s ) {
1687 if ( is_null( $s ) ) {
1688 return 'NULL';
1689 } else {
1690 # This will also quote numeric values. This should be harmless,
1691 # and protects against weird problems that occur when they really
1692 # _are_ strings such as article titles and string->number->string
1693 # conversion is not 1:1.
1694 return "'" . $this->strencode( $s ) . "'";
1695 }
1696 }
1697
1698 /**
1699 * Escape string for safe LIKE usage
1700 */
1701 function escapeLike( $s ) {
1702 $s=$this->strencode( $s );
1703 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1704 return $s;
1705 }
1706
1707 /**
1708 * Returns an appropriately quoted sequence value for inserting a new row.
1709 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1710 * subclass will return an integer, and save the value for insertId()
1711 */
1712 function nextSequenceValue( $seqName ) {
1713 return NULL;
1714 }
1715
1716 /**
1717 * USE INDEX clause
1718 * PostgreSQL doesn't have them and returns ""
1719 */
1720 function useIndexClause( $index ) {
1721 return "FORCE INDEX ($index)";
1722 }
1723
1724 /**
1725 * REPLACE query wrapper
1726 * PostgreSQL simulates this with a DELETE followed by INSERT
1727 * $row is the row to insert, an associative array
1728 * $uniqueIndexes is an array of indexes. Each element may be either a
1729 * field name or an array of field names
1730 *
1731 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1732 * However if you do this, you run the risk of encountering errors which wouldn't have
1733 * occurred in MySQL
1734 *
1735 * @todo migrate comment to phodocumentor format
1736 */
1737 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1738 $table = $this->tableName( $table );
1739
1740 # Single row case
1741 if ( !is_array( reset( $rows ) ) ) {
1742 $rows = array( $rows );
1743 }
1744
1745 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1746 $first = true;
1747 foreach ( $rows as $row ) {
1748 if ( $first ) {
1749 $first = false;
1750 } else {
1751 $sql .= ',';
1752 }
1753 $sql .= '(' . $this->makeList( $row ) . ')';
1754 }
1755 return $this->query( $sql, $fname );
1756 }
1757
1758 /**
1759 * DELETE where the condition is a join
1760 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1761 *
1762 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1763 * join condition matches, set $conds='*'
1764 *
1765 * DO NOT put the join condition in $conds
1766 *
1767 * @param string $delTable The table to delete from.
1768 * @param string $joinTable The other table.
1769 * @param string $delVar The variable to join on, in the first table.
1770 * @param string $joinVar The variable to join on, in the second table.
1771 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1772 */
1773 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1774 if ( !$conds ) {
1775 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1776 }
1777
1778 $delTable = $this->tableName( $delTable );
1779 $joinTable = $this->tableName( $joinTable );
1780 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1781 if ( $conds != '*' ) {
1782 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1783 }
1784
1785 return $this->query( $sql, $fname );
1786 }
1787
1788 /**
1789 * Returns the size of a text field, or -1 for "unlimited"
1790 */
1791 function textFieldSize( $table, $field ) {
1792 $table = $this->tableName( $table );
1793 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1794 $res = $this->query( $sql, 'Database::textFieldSize' );
1795 $row = $this->fetchObject( $res );
1796 $this->freeResult( $res );
1797
1798 $m = array();
1799 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1800 $size = $m[1];
1801 } else {
1802 $size = -1;
1803 }
1804 return $size;
1805 }
1806
1807 /**
1808 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1809 */
1810 function lowPriorityOption() {
1811 return 'LOW_PRIORITY';
1812 }
1813
1814 /**
1815 * DELETE query wrapper
1816 *
1817 * Use $conds == "*" to delete all rows
1818 */
1819 function delete( $table, $conds, $fname = 'Database::delete' ) {
1820 if ( !$conds ) {
1821 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1822 }
1823 $table = $this->tableName( $table );
1824 $sql = "DELETE FROM $table";
1825 if ( $conds != '*' ) {
1826 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1827 }
1828 return $this->query( $sql, $fname );
1829 }
1830
1831 /**
1832 * INSERT SELECT wrapper
1833 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1834 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1835 * $conds may be "*" to copy the whole table
1836 * srcTable may be an array of tables.
1837 */
1838 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1839 $insertOptions = array(), $selectOptions = array() )
1840 {
1841 $destTable = $this->tableName( $destTable );
1842 if ( is_array( $insertOptions ) ) {
1843 $insertOptions = implode( ' ', $insertOptions );
1844 }
1845 if( !is_array( $selectOptions ) ) {
1846 $selectOptions = array( $selectOptions );
1847 }
1848 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1849 if( is_array( $srcTable ) ) {
1850 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1851 } else {
1852 $srcTable = $this->tableName( $srcTable );
1853 }
1854 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1855 " SELECT $startOpts " . implode( ',', $varMap ) .
1856 " FROM $srcTable $useIndex ";
1857 if ( $conds != '*' ) {
1858 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1859 }
1860 $sql .= " $tailOpts";
1861 return $this->query( $sql, $fname );
1862 }
1863
1864 /**
1865 * Construct a LIMIT query with optional offset
1866 * This is used for query pages
1867 * $sql string SQL query we will append the limit too
1868 * $limit integer the SQL limit
1869 * $offset integer the SQL offset (default false)
1870 */
1871 function limitResult($sql, $limit, $offset=false) {
1872 if( !is_numeric($limit) ) {
1873 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1874 }
1875 return " $sql LIMIT "
1876 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1877 . "{$limit} ";
1878 }
1879 function limitResultForUpdate($sql, $num) {
1880 return $this->limitResult($sql, $num, 0);
1881 }
1882
1883 /**
1884 * Returns an SQL expression for a simple conditional.
1885 * Uses IF on MySQL.
1886 *
1887 * @param string $cond SQL expression which will result in a boolean value
1888 * @param string $trueVal SQL expression to return if true
1889 * @param string $falseVal SQL expression to return if false
1890 * @return string SQL fragment
1891 */
1892 function conditional( $cond, $trueVal, $falseVal ) {
1893 return " IF($cond, $trueVal, $falseVal) ";
1894 }
1895
1896 /**
1897 * Determines if the last failure was due to a deadlock
1898 */
1899 function wasDeadlock() {
1900 return $this->lastErrno() == 1213;
1901 }
1902
1903 /**
1904 * Perform a deadlock-prone transaction.
1905 *
1906 * This function invokes a callback function to perform a set of write
1907 * queries. If a deadlock occurs during the processing, the transaction
1908 * will be rolled back and the callback function will be called again.
1909 *
1910 * Usage:
1911 * $dbw->deadlockLoop( callback, ... );
1912 *
1913 * Extra arguments are passed through to the specified callback function.
1914 *
1915 * Returns whatever the callback function returned on its successful,
1916 * iteration, or false on error, for example if the retry limit was
1917 * reached.
1918 */
1919 function deadlockLoop() {
1920 $myFname = 'Database::deadlockLoop';
1921
1922 $this->begin();
1923 $args = func_get_args();
1924 $function = array_shift( $args );
1925 $oldIgnore = $this->ignoreErrors( true );
1926 $tries = DEADLOCK_TRIES;
1927 if ( is_array( $function ) ) {
1928 $fname = $function[0];
1929 } else {
1930 $fname = $function;
1931 }
1932 do {
1933 $retVal = call_user_func_array( $function, $args );
1934 $error = $this->lastError();
1935 $errno = $this->lastErrno();
1936 $sql = $this->lastQuery();
1937
1938 if ( $errno ) {
1939 if ( $this->wasDeadlock() ) {
1940 # Retry
1941 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1942 } else {
1943 $this->reportQueryError( $error, $errno, $sql, $fname );
1944 }
1945 }
1946 } while( $this->wasDeadlock() && --$tries > 0 );
1947 $this->ignoreErrors( $oldIgnore );
1948 if ( $tries <= 0 ) {
1949 $this->query( 'ROLLBACK', $myFname );
1950 $this->reportQueryError( $error, $errno, $sql, $fname );
1951 return false;
1952 } else {
1953 $this->query( 'COMMIT', $myFname );
1954 return $retVal;
1955 }
1956 }
1957
1958 /**
1959 * Do a SELECT MASTER_POS_WAIT()
1960 *
1961 * @param string $file the binlog file
1962 * @param string $pos the binlog position
1963 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1964 */
1965 function masterPosWait( $file, $pos, $timeout ) {
1966 $fname = 'Database::masterPosWait';
1967 wfProfileIn( $fname );
1968
1969
1970 # Commit any open transactions
1971 $this->immediateCommit();
1972
1973 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1974 $encFile = $this->strencode( $file );
1975 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1976 $res = $this->doQuery( $sql );
1977 if ( $res && $row = $this->fetchRow( $res ) ) {
1978 $this->freeResult( $res );
1979 wfProfileOut( $fname );
1980 return $row[0];
1981 } else {
1982 wfProfileOut( $fname );
1983 return false;
1984 }
1985 }
1986
1987 /**
1988 * Get the position of the master from SHOW SLAVE STATUS
1989 */
1990 function getSlavePos() {
1991 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1992 $row = $this->fetchObject( $res );
1993 if ( $row ) {
1994 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1995 } else {
1996 return array( false, false );
1997 }
1998 }
1999
2000 /**
2001 * Get the position of the master from SHOW MASTER STATUS
2002 */
2003 function getMasterPos() {
2004 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
2005 $row = $this->fetchObject( $res );
2006 if ( $row ) {
2007 return array( $row->File, $row->Position );
2008 } else {
2009 return array( false, false );
2010 }
2011 }
2012
2013 /**
2014 * Begin a transaction, committing any previously open transaction
2015 */
2016 function begin( $fname = 'Database::begin' ) {
2017 $this->query( 'BEGIN', $fname );
2018 $this->mTrxLevel = 1;
2019 }
2020
2021 /**
2022 * End a transaction
2023 */
2024 function commit( $fname = 'Database::commit' ) {
2025 $this->query( 'COMMIT', $fname );
2026 $this->mTrxLevel = 0;
2027 }
2028
2029 /**
2030 * Rollback a transaction
2031 */
2032 function rollback( $fname = 'Database::rollback' ) {
2033 $this->query( 'ROLLBACK', $fname );
2034 $this->mTrxLevel = 0;
2035 }
2036
2037 /**
2038 * Begin a transaction, committing any previously open transaction
2039 * @deprecated use begin()
2040 */
2041 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2042 $this->begin();
2043 }
2044
2045 /**
2046 * Commit transaction, if one is open
2047 * @deprecated use commit()
2048 */
2049 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2050 $this->commit();
2051 }
2052
2053 /**
2054 * Return MW-style timestamp used for MySQL schema
2055 */
2056 function timestamp( $ts=0 ) {
2057 return wfTimestamp(TS_MW,$ts);
2058 }
2059
2060 /**
2061 * Local database timestamp format or null
2062 */
2063 function timestampOrNull( $ts = null ) {
2064 if( is_null( $ts ) ) {
2065 return null;
2066 } else {
2067 return $this->timestamp( $ts );
2068 }
2069 }
2070
2071 /**
2072 * @todo document
2073 */
2074 function resultObject( $result ) {
2075 if( empty( $result ) ) {
2076 return false;
2077 } elseif ( $result instanceof ResultWrapper ) {
2078 return $result;
2079 } elseif ( $result === true ) {
2080 // Successful write query
2081 return $result;
2082 } else {
2083 return new ResultWrapper( $this, $result );
2084 }
2085 }
2086
2087 /**
2088 * Return aggregated value alias
2089 */
2090 function aggregateValue ($valuedata,$valuename='value') {
2091 return $valuename;
2092 }
2093
2094 /**
2095 * @return string wikitext of a link to the server software's web site
2096 */
2097 function getSoftwareLink() {
2098 return "[http://www.mysql.com/ MySQL]";
2099 }
2100
2101 /**
2102 * @return string Version information from the database
2103 */
2104 function getServerVersion() {
2105 return mysql_get_server_info( $this->mConn );
2106 }
2107
2108 /**
2109 * Ping the server and try to reconnect if it there is no connection
2110 */
2111 function ping() {
2112 if( function_exists( 'mysql_ping' ) ) {
2113 return mysql_ping( $this->mConn );
2114 } else {
2115 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2116 return true;
2117 }
2118 }
2119
2120 /**
2121 * Get slave lag.
2122 * At the moment, this will only work if the DB user has the PROCESS privilege
2123 */
2124 function getLag() {
2125 $res = $this->query( 'SHOW PROCESSLIST' );
2126 # Find slave SQL thread
2127 while ( $row = $this->fetchObject( $res ) ) {
2128 /* This should work for most situations - when default db
2129 * for thread is not specified, it had no events executed,
2130 * and therefore it doesn't know yet how lagged it is.
2131 *
2132 * Relay log I/O thread does not select databases.
2133 */
2134 if ( $row->User == 'system user' &&
2135 $row->State != 'Waiting for master to send event' &&
2136 $row->State != 'Connecting to master' &&
2137 $row->State != 'Queueing master event to the relay log' &&
2138 $row->State != 'Waiting for master update' &&
2139 $row->State != 'Requesting binlog dump'
2140 ) {
2141 # This is it, return the time (except -ve)
2142 if ( $row->Time > 0x7fffffff ) {
2143 return false;
2144 } else {
2145 return $row->Time;
2146 }
2147 }
2148 }
2149 return false;
2150 }
2151
2152 /**
2153 * Get status information from SHOW STATUS in an associative array
2154 */
2155 function getStatus($which="%") {
2156 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2157 $status = array();
2158 while ( $row = $this->fetchObject( $res ) ) {
2159 $status[$row->Variable_name] = $row->Value;
2160 }
2161 return $status;
2162 }
2163
2164 /**
2165 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2166 */
2167 function maxListLen() {
2168 return 0;
2169 }
2170
2171 function encodeBlob($b) {
2172 return $b;
2173 }
2174
2175 function decodeBlob($b) {
2176 return $b;
2177 }
2178
2179 /**
2180 * Override database's default connection timeout.
2181 * May be useful for very long batch queries such as
2182 * full-wiki dumps, where a single query reads out
2183 * over hours or days.
2184 * @param int $timeout in seconds
2185 */
2186 public function setTimeout( $timeout ) {
2187 $this->query( "SET net_read_timeout=$timeout" );
2188 $this->query( "SET net_write_timeout=$timeout" );
2189 }
2190
2191 /**
2192 * Read and execute SQL commands from a file.
2193 * Returns true on success, error string on failure
2194 * @param string $filename File name to open
2195 * @param callback $lineCallback Optional function called before reading each line
2196 * @param callback $resultCallback Optional function called for each MySQL result
2197 */
2198 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2199 $fp = fopen( $filename, 'r' );
2200 if ( false === $fp ) {
2201 return "Could not open \"{$filename}\".\n";
2202 }
2203 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2204 fclose( $fp );
2205 return $error;
2206 }
2207
2208 /**
2209 * Read and execute commands from an open file handle
2210 * Returns true on success, error string on failure
2211 * @param string $fp File handle
2212 * @param callback $lineCallback Optional function called before reading each line
2213 * @param callback $resultCallback Optional function called for each MySQL result
2214 */
2215 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2216 $cmd = "";
2217 $done = false;
2218 $dollarquote = false;
2219
2220 while ( ! feof( $fp ) ) {
2221 if ( $lineCallback ) {
2222 call_user_func( $lineCallback );
2223 }
2224 $line = trim( fgets( $fp, 1024 ) );
2225 $sl = strlen( $line ) - 1;
2226
2227 if ( $sl < 0 ) { continue; }
2228 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2229
2230 ## Allow dollar quoting for function declarations
2231 if (substr($line,0,4) == '$mw$') {
2232 if ($dollarquote) {
2233 $dollarquote = false;
2234 $done = true;
2235 }
2236 else {
2237 $dollarquote = true;
2238 }
2239 }
2240 else if (!$dollarquote) {
2241 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2242 $done = true;
2243 $line = substr( $line, 0, $sl );
2244 }
2245 }
2246
2247 if ( '' != $cmd ) { $cmd .= ' '; }
2248 $cmd .= "$line\n";
2249
2250 if ( $done ) {
2251 $cmd = str_replace(';;', ";", $cmd);
2252 $cmd = $this->replaceVars( $cmd );
2253 $res = $this->query( $cmd, __METHOD__, true );
2254 if ( $resultCallback ) {
2255 call_user_func( $resultCallback, $res );
2256 }
2257
2258 if ( false === $res ) {
2259 $err = $this->lastError();
2260 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2261 }
2262
2263 $cmd = '';
2264 $done = false;
2265 }
2266 }
2267 return true;
2268 }
2269
2270
2271 /**
2272 * Replace variables in sourced SQL
2273 */
2274 protected function replaceVars( $ins ) {
2275 $varnames = array(
2276 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2277 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2278 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2279 );
2280
2281 // Ordinary variables
2282 foreach ( $varnames as $var ) {
2283 if( isset( $GLOBALS[$var] ) ) {
2284 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2285 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2286 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2287 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2288 }
2289 }
2290
2291 // Table prefixes
2292 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2293 array( &$this, 'tableNameCallback' ), $ins );
2294 return $ins;
2295 }
2296
2297 /**
2298 * Table name callback
2299 * @private
2300 */
2301 protected function tableNameCallback( $matches ) {
2302 return $this->tableName( $matches[1] );
2303 }
2304
2305 /*
2306 * Build a concatenation list to feed into a SQL query
2307 */
2308 function buildConcat( $stringList ) {
2309 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2310 }
2311
2312 }
2313
2314 /**
2315 * Database abstraction object for mySQL
2316 * Inherit all methods and properties of Database::Database()
2317 *
2318 * @addtogroup Database
2319 * @see Database
2320 */
2321 class DatabaseMysql extends Database {
2322 # Inherit all
2323 }
2324
2325
2326 /**
2327 * Result wrapper for grabbing data queried by someone else
2328 * @addtogroup Database
2329 */
2330 class ResultWrapper implements Iterator {
2331 var $db, $result, $pos = 0, $currentRow = null;
2332
2333 /**
2334 * Create a new result object from a result resource and a Database object
2335 */
2336 function ResultWrapper( $database, $result ) {
2337 $this->db = $database;
2338 if ( $result instanceof ResultWrapper ) {
2339 $this->result = $result->result;
2340 } else {
2341 $this->result = $result;
2342 }
2343 }
2344
2345 /**
2346 * Get the number of rows in a result object
2347 */
2348 function numRows() {
2349 return $this->db->numRows( $this->result );
2350 }
2351
2352 /**
2353 * Fetch the next row from the given result object, in object form.
2354 * Fields can be retrieved with $row->fieldname, with fields acting like
2355 * member variables.
2356 *
2357 * @param $res SQL result object as returned from Database::query(), etc.
2358 * @return MySQL row object
2359 * @throws DBUnexpectedError Thrown if the database returns an error
2360 */
2361 function fetchObject() {
2362 return $this->db->fetchObject( $this->result );
2363 }
2364
2365 /**
2366 * Fetch the next row from the given result object, in associative array
2367 * form. Fields are retrieved with $row['fieldname'].
2368 *
2369 * @param $res SQL result object as returned from Database::query(), etc.
2370 * @return MySQL row object
2371 * @throws DBUnexpectedError Thrown if the database returns an error
2372 */
2373 function fetchRow() {
2374 return $this->db->fetchRow( $this->result );
2375 }
2376
2377 /**
2378 * Free a result object
2379 */
2380 function free() {
2381 $this->db->freeResult( $this->result );
2382 unset( $this->result );
2383 unset( $this->db );
2384 }
2385
2386 /**
2387 * Change the position of the cursor in a result object
2388 * See mysql_data_seek()
2389 */
2390 function seek( $row ) {
2391 $this->db->dataSeek( $this->result, $row );
2392 }
2393
2394 /*********************
2395 * Iterator functions
2396 * Note that using these in combination with the non-iterator functions
2397 * above may cause rows to be skipped or repeated.
2398 */
2399
2400 function rewind() {
2401 if ($this->numRows()) {
2402 $this->db->dataSeek($this->result, 0);
2403 }
2404 $this->pos = 0;
2405 $this->currentRow = null;
2406 }
2407
2408 function current() {
2409 if ( is_null( $this->currentRow ) ) {
2410 $this->next();
2411 }
2412 return $this->currentRow;
2413 }
2414
2415 function key() {
2416 return $this->pos;
2417 }
2418
2419 function next() {
2420 $this->pos++;
2421 $this->currentRow = $this->fetchObject();
2422 return $this->currentRow;
2423 }
2424
2425 function valid() {
2426 return $this->current() !== false;
2427 }
2428 }
2429
2430