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