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