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