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