Correcting bugs due to double-prefixing table names. Removing obsolete Database membe...
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @version # $Id$
6 * @package MediaWiki
7 */
8
9 /**
10 * Depends on the CacheManager
11 */
12 require_once( 'CacheManager.php' );
13
14 /** See Database::makeList() */
15 define( 'LIST_COMMA', 0 );
16 define( 'LIST_AND', 1 );
17 define( 'LIST_SET', 2 );
18 define( 'LIST_NAMES', 3);
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 /**
28 * Database abstraction object
29 * @package MediaWiki
30 * @version # $Id$
31 */
32 class Database {
33
34 #------------------------------------------------------------------------------
35 # Variables
36 #------------------------------------------------------------------------------
37 /**#@+
38 * @access private
39 */
40 var $mLastQuery = '';
41
42 var $mServer, $mUser, $mPassword, $mConn, $mDBname;
43 var $mOut, $mOpened = false;
44
45 var $mFailFunction;
46 var $mTablePrefix;
47 var $mFlags;
48 var $mTrxLevel = 0;
49 /**#@-*/
50
51 #------------------------------------------------------------------------------
52 # Accessors
53 #------------------------------------------------------------------------------
54 # These optionally set a variable and return the previous state
55
56 /**
57 * Fail function, takes a Database as a parameter
58 * Set to false for default, 1 for ignore errors
59 */
60 function failFunction( $function = NULL ) {
61 return wfSetVar( $this->mFailFunction, $function );
62 }
63
64 /**
65 * Output page, used for reporting errors
66 * FALSE means discard output
67 */
68 function &setOutputPage( &$out ) {
69 $this->mOut =& $out;
70 }
71
72 /**
73 * Boolean, controls output of large amounts of debug information
74 */
75 function debug( $debug = NULL ) {
76 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
77 }
78
79 /**
80 * Turns buffering of SQL result sets on (true) or off (false).
81 * Default is "on" and it should not be changed without good reasons.
82 */
83 function bufferResults( $buffer = NULL ) {
84 if ( is_null( $buffer ) ) {
85 return !(bool)( $this->mFlags & DBO_NOBUFFER );
86 } else {
87 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
88 }
89 }
90
91 /**
92 * Turns on (false) or off (true) the automatic generation and sending
93 * of a "we're sorry, but there has been a database error" page on
94 * database errors. Default is on (false). When turned off, the
95 * code should use wfLastErrno() and wfLastError() to handle the
96 * situation as appropriate.
97 */
98 function ignoreErrors( $ignoreErrors = NULL ) {
99 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
100 }
101
102 /**
103 * The current depth of nested transactions
104 * @param integer $level
105 */
106 function trxLevel( $level = NULL ) {
107 return wfSetVar( $this->mTrxLevel, $level );
108 }
109
110 /**#@+
111 * Get function
112 */
113 function lastQuery() { return $this->mLastQuery; }
114 function isOpen() { return $this->mOpened; }
115 /**#@-*/
116
117 #------------------------------------------------------------------------------
118 # Other functions
119 #------------------------------------------------------------------------------
120
121 /**#@+
122 * @param string $server database server host
123 * @param string $user database user name
124 * @param string $password database user password
125 * @param string $dbname database name
126 */
127
128 /**
129 * @param failFunction
130 * @param $flags
131 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
132 */
133 function Database( $server = false, $user = false, $password = false, $dbName = false,
134 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
135
136 global $wgOut, $wgDBprefix, $wgCommandLineMode;
137 # Can't get a reference if it hasn't been set yet
138 if ( !isset( $wgOut ) ) {
139 $wgOut = NULL;
140 }
141 $this->mOut =& $wgOut;
142
143 $this->mFailFunction = $failFunction;
144 $this->mFlags = $flags;
145
146 if ( $this->mFlags & DBO_DEFAULT ) {
147 if ( $wgCommandLineMode ) {
148 $this->mFlags &= ~DBO_TRX;
149 } else {
150 $this->mFlags |= DBO_TRX;
151 }
152 }
153
154 /** Get the default table prefix*/
155 if ( $tablePrefix == 'get from global' ) {
156 $this->mTablePrefix = $wgDBprefix;
157 } else {
158 $this->mTablePrefix = $tablePrefix;
159 }
160
161 if ( $server ) {
162 $this->open( $server, $user, $password, $dbName );
163 }
164 }
165
166 /**
167 * @static
168 * @param failFunction
169 * @param $flags
170 */
171 function newFromParams( $server, $user, $password, $dbName,
172 $failFunction = false, $flags = 0 )
173 {
174 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
175 }
176
177 /**
178 * Usually aborts on failure
179 * If the failFunction is set to a non-zero integer, returns success
180 */
181 function open( $server, $user, $password, $dbName ) {
182 # Test for missing mysql.so
183 # Otherwise we get a suppressed fatal error, which is very hard to track down
184 if ( !function_exists( 'mysql_connect' ) ) {
185 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
186 }
187
188 $this->close();
189 $this->mServer = $server;
190 $this->mUser = $user;
191 $this->mPassword = $password;
192 $this->mDBname = $dbName;
193
194 $success = false;
195
196 @/**/$this->mConn = mysql_connect( $server, $user, $password );
197 if ( $dbName != '' ) {
198 if ( $this->mConn !== false ) {
199 $success = @/**/mysql_select_db( $dbName, $this->mConn );
200 if ( !$success ) {
201 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
202 }
203 } else {
204 wfDebug( "DB connection error\n" );
205 wfDebug( "Server: $server, User: $user, Password: " .
206 substr( $password, 0, 3 ) . "...\n" );
207 $success = false;
208 }
209 } else {
210 # Delay USE query
211 $success = !!$this->mConn;
212 }
213
214 if ( !$success ) {
215 $this->reportConnectionError();
216 $this->close();
217 }
218 $this->mOpened = $success;
219 return $success;
220 }
221 /**#@-*/
222
223 /**
224 * Closes a database connection.
225 * if it is open : commits any open transactions
226 *
227 * @return bool operation success. true if already closed.
228 */
229 function close()
230 {
231 $this->mOpened = false;
232 if ( $this->mConn ) {
233 if ( $this->trxLevel() ) {
234 $this->immediateCommit();
235 }
236 return mysql_close( $this->mConn );
237 } else {
238 return true;
239 }
240 }
241
242 /**
243 * @access private
244 * @param string $msg error message ?
245 * @todo parameter $msg is not used
246 */
247 function reportConnectionError( $msg = '') {
248 if ( $this->mFailFunction ) {
249 if ( !is_int( $this->mFailFunction ) ) {
250 $ff = $this->mFailFunction;
251 $ff( $this, mysql_error() );
252 }
253 } else {
254 wfEmergencyAbort( $this, mysql_error() );
255 }
256 }
257
258 /**
259 * Usually aborts on failure
260 * If errors are explicitly ignored, returns success
261 */
262 function query( $sql, $fname = '', $tempIgnore = false ) {
263 global $wgProfiling, $wgCommandLineMode;
264
265 if ( $wgProfiling ) {
266 # generalizeSQL will probably cut down the query to reasonable
267 # logging size most of the time. The substr is really just a sanity check.
268 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
269 wfProfileIn( $profName );
270 }
271
272 $this->mLastQuery = $sql;
273
274 if ( $this->debug() ) {
275 $sqlx = substr( $sql, 0, 500 );
276 $sqlx = wordwrap(strtr($sqlx,"\t\n",' '));
277 wfDebug( "SQL: $sqlx\n" );
278 }
279 # Add a comment for easy SHOW PROCESSLIST interpretation
280 if ( $fname ) {
281 $commentedSql = "/* $fname */ $sql";
282 } else {
283 $commentedSql = $sql;
284 }
285
286 # If DBO_TRX is set, start a transaction
287 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
288 $this->begin();
289 }
290
291 # Do the query and handle errors
292 $ret = $this->doQuery( $commentedSql );
293 if ( false === $ret ) {
294 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
295 }
296
297 if ( $wgProfiling ) {
298 wfProfileOut( $profName );
299 }
300 return $ret;
301 }
302
303 /**
304 * The DBMS-dependent part of query()
305 * @param string $sql SQL query.
306 */
307 function doQuery( $sql ) {
308 if( $this->bufferResults() ) {
309 $ret = mysql_query( $sql, $this->mConn );
310 } else {
311 $ret = mysql_unbuffered_query( $sql, $this->mConn );
312 }
313 return $ret;
314 }
315
316 /**
317 * @param $error
318 * @param $errno
319 * @param $sql
320 * @param string $fname
321 * @param bool $tempIgnore
322 */
323 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
324 global $wgCommandLineMode, $wgFullyInitialised;
325 # Ignore errors during error handling to avoid infinite recursion
326 $ignore = $this->ignoreErrors( true );
327
328 if( $ignore || $tempIgnore ) {
329 wfDebug("SQL ERROR (ignored): " . $error . "\n");
330 } else {
331 $sql1line = str_replace( "\n", "\\n", $sql );
332 wfLogDBError("$fname\t$errno\t$error\t$sql1line\n");
333 wfDebug("SQL ERROR: " . $error . "\n");
334 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
335 $message = "A database error has occurred\n" .
336 "Query: $sql\n" .
337 "Function: $fname\n" .
338 "Error: $errno $error\n";
339 if ( !$wgCommandLineMode ) {
340 $message = nl2br( $message );
341 }
342 wfDebugDieBacktrace( $message );
343 } else {
344 // this calls wfAbruptExit()
345 $this->mOut->databaseError( $fname, $sql, $error, $errno );
346 }
347 }
348 $this->ignoreErrors( $ignore );
349 }
350
351
352 /**
353 * Intended to be compatible with the PEAR::DB wrapper functions.
354 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
355 *
356 * ? = scalar value, quoted as necessary
357 * ! = raw SQL bit (a function for instance)
358 * & = filename; reads the file and inserts as a blob
359 * (we don't use this though...)
360 */
361 function prepare( $sql, $func = 'Database::prepare' ) {
362 /* MySQL doesn't support prepared statements (yet), so just
363 pack up the query for reference. We'll manually replace
364 the bits later. */
365 return array( 'query' => $sql, 'func' => $func );
366 }
367
368 function freePrepared( $prepared ) {
369 /* No-op for MySQL */
370 }
371
372 /**
373 * Execute a prepared query with the various arguments
374 * @param string $prepared the prepared sql
375 * @param mixed $args Either an array here, or put scalars as varargs
376 */
377 function execute( $prepared, $args = null ) {
378 if( !is_array( $args ) ) {
379 # Pull the var args
380 $args = func_get_args();
381 array_shift( $args );
382 }
383 $sql = $this->fillPrepared( $prepared['query'], $args );
384 return $this->query( $sql, $prepared['func'] );
385 }
386
387 /**
388 * Prepare & execute an SQL statement, quoting and inserting arguments
389 * in the appropriate places.
390 * @param
391 */
392 function safeQuery( $query, $args = null ) {
393 $prepared = $this->prepare( $query, 'Database::safeQuery' );
394 if( !is_array( $args ) ) {
395 # Pull the var args
396 $args = func_get_args();
397 array_shift( $args );
398 }
399 $retval = $this->execute( $prepared, $args );
400 $this->freePrepared( $prepared );
401 return $retval;
402 }
403
404 /**
405 * For faking prepared SQL statements on DBs that don't support
406 * it directly.
407 * @param string $preparedSql - a 'preparable' SQL statement
408 * @param array $args - array of arguments to fill it with
409 * @return string executable SQL
410 */
411 function fillPrepared( $preparedQuery, $args ) {
412 $n = 0;
413 reset( $args );
414 $this->preparedArgs =& $args;
415 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
416 array( &$this, 'fillPreparedArg' ), $preparedQuery );
417 }
418
419 /**
420 * preg_callback func for fillPrepared()
421 * The arguments should be in $this->preparedArgs and must not be touched
422 * while we're doing this.
423 *
424 * @param array $matches
425 * @return string
426 * @access private
427 */
428 function fillPreparedArg( $matches ) {
429 switch( $matches[1] ) {
430 case '\\?': return '?';
431 case '\\!': return '!';
432 case '\\&': return '&';
433 }
434 list( $n, $arg ) = each( $this->preparedArgs );
435 switch( $matches[1] ) {
436 case '?': return $this->addQuotes( $arg );
437 case '!': return $arg;
438 case '&':
439 # return $this->addQuotes( file_get_contents( $arg ) );
440 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
441 default:
442 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
443 }
444 }
445
446 /**#@+
447 * @param mixed $res A SQL result
448 */
449 /**
450 * Free a result object
451 */
452 function freeResult( $res ) {
453 if ( !@/**/mysql_free_result( $res ) ) {
454 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
455 }
456 }
457
458 /**
459 * Fetch the next row from the given result object, in object form
460 */
461 function fetchObject( $res ) {
462 @/**/$row = mysql_fetch_object( $res );
463 if( mysql_errno() ) {
464 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
465 }
466 return $row;
467 }
468
469 /**
470 * Fetch the next row from the given result object
471 * Returns an array
472 */
473 function fetchRow( $res ) {
474 @/**/$row = mysql_fetch_array( $res );
475 if (mysql_errno() ) {
476 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
477 }
478 return $row;
479 }
480
481 /**
482 * Get the number of rows in a result object
483 */
484 function numRows( $res ) {
485 @/**/$n = mysql_num_rows( $res );
486 if( mysql_errno() ) {
487 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
488 }
489 return $n;
490 }
491
492 /**
493 * Get the number of fields in a result object
494 * See documentation for mysql_num_fields()
495 */
496 function numFields( $res ) { return mysql_num_fields( $res ); }
497
498 /**
499 * Get a field name in a result object
500 * See documentation for mysql_field_name()
501 */
502 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
503
504 /**
505 * Get the inserted value of an auto-increment row
506 *
507 * The value inserted should be fetched from nextSequenceValue()
508 *
509 * Example:
510 * $id = $dbw->nextSequenceValue('cur_cur_id_seq');
511 * $dbw->insert('cur',array('cur_id' => $id));
512 * $id = $dbw->insertId();
513 */
514 function insertId() { return mysql_insert_id( $this->mConn ); }
515
516 /**
517 * Change the position of the cursor in a result object
518 * See mysql_data_seek()
519 */
520 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
521
522 /**
523 * Get the last error number
524 * See mysql_errno()
525 */
526 function lastErrno() { return mysql_errno(); }
527
528 /**
529 * Get a description of the last error
530 * See mysql_error() for more details
531 */
532 function lastError() { return mysql_error(); }
533
534 /**
535 * Get the number of rows affected by the last write query
536 * See mysql_affected_rows() for more details
537 */
538 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
539 /**#@-*/ // end of template : @param $result
540
541 /**
542 * Simple UPDATE wrapper
543 * Usually aborts on failure
544 * If errors are explicitly ignored, returns success
545 *
546 * This function exists for historical reasons, Database::update() has a more standard
547 * calling convention and feature set
548 */
549 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
550 {
551 $table = $this->tableName( $table );
552 $sql = "UPDATE $table SET $var = '" .
553 $this->strencode( $value ) . "' WHERE ($cond)";
554 return !!$this->query( $sql, DB_MASTER, $fname );
555 }
556
557 /**
558 * Simple SELECT wrapper, returns a single field, input must be encoded
559 * Usually aborts on failure
560 * If errors are explicitly ignored, returns FALSE on failure
561 */
562 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
563 if ( !is_array( $options ) ) {
564 $options = array( $options );
565 }
566 $options['LIMIT'] = 1;
567
568 $res = $this->select( $table, $var, $cond, $fname, $options );
569 if ( $res === false || !$this->numRows( $res ) ) {
570 return false;
571 }
572 $row = $this->fetchRow( $res );
573 if ( $row !== false ) {
574 $this->freeResult( $res );
575 return $row[0];
576 } else {
577 return false;
578 }
579 }
580
581 /**
582 * Returns an optional USE INDEX clause to go after the table, and a
583 * string to go at the end of the query
584 */
585 function makeSelectOptions( $options ) {
586 if ( !is_array( $options ) ) {
587 $options = array( $options );
588 }
589
590 $tailOpts = '';
591
592 if ( isset( $options['ORDER BY'] ) ) {
593 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
594 }
595 if ( isset( $options['LIMIT'] ) ) {
596 $tailOpts .= " LIMIT {$options['LIMIT']}";
597 }
598
599 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
600 $tailOpts .= ' FOR UPDATE';
601 }
602
603 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
604 $tailOpts .= ' LOCK IN SHARE MODE';
605 }
606
607 if ( isset( $options['USE INDEX'] ) ) {
608 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
609 } else {
610 $useIndex = '';
611 }
612 return array( $useIndex, $tailOpts );
613 }
614
615 /**
616 * SELECT wrapper
617 */
618 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
619 {
620 if ( is_array( $vars ) ) {
621 $vars = implode( ',', $vars );
622 }
623 if( is_array( $table ) ) {
624 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
625 } elseif ($table!='') {
626 $from = ' FROM ' .$this->tableName( $table );
627 } else {
628 $from = '';
629 }
630
631 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
632
633 if ( $conds !== false && $conds != '' ) {
634 if ( is_array( $conds ) ) {
635 $conds = $this->makeList( $conds, LIST_AND );
636 }
637 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
638 } else {
639 $sql = "SELECT $vars $from $useIndex $tailOpts";
640 }
641 return $this->query( $sql, $fname );
642 }
643
644 /**
645 * Single row SELECT wrapper
646 * Aborts or returns FALSE on error
647 *
648 * $vars: the selected variables
649 * $conds: a condition map, terms are ANDed together.
650 * Items with numeric keys are taken to be literal conditions
651 * Takes an array of selected variables, and a condition map, which is ANDed
652 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
653 * would return an object where $obj->cur_id is the ID of the Astronomy article
654 *
655 * @todo migrate documentation to phpdocumentor format
656 */
657 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
658 $options['LIMIT'] = 1;
659 $res = $this->select( $table, $vars, $conds, $fname, $options );
660 if ( $res === false || !$this->numRows( $res ) ) {
661 return false;
662 }
663 $obj = $this->fetchObject( $res );
664 $this->freeResult( $res );
665 return $obj;
666
667 }
668
669 /**
670 * Removes most variables from an SQL query and replaces them with X or N for numbers.
671 * It's only slightly flawed. Don't use for anything important.
672 *
673 * @param string $sql A SQL Query
674 * @static
675 */
676 function generalizeSQL( $sql ) {
677 # This does the same as the regexp below would do, but in such a way
678 # as to avoid crashing php on some large strings.
679 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
680
681 $sql = str_replace ( "\\\\", '', $sql);
682 $sql = str_replace ( "\\'", '', $sql);
683 $sql = str_replace ( "\\\"", '', $sql);
684 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
685 $sql = preg_replace ('/".*"/s', "'X'", $sql);
686
687 # All newlines, tabs, etc replaced by single space
688 $sql = preg_replace ( "/\s+/", ' ', $sql);
689
690 # All numbers => N
691 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
692
693 return $sql;
694 }
695
696 /**
697 * Determines whether a field exists in a table
698 * Usually aborts on failure
699 * If errors are explicitly ignored, returns NULL on failure
700 */
701 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
702 $table = $this->tableName( $table );
703 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
704 if ( !$res ) {
705 return NULL;
706 }
707
708 $found = false;
709
710 while ( $row = $this->fetchObject( $res ) ) {
711 if ( $row->Field == $field ) {
712 $found = true;
713 break;
714 }
715 }
716 return $found;
717 }
718
719 /**
720 * Determines whether an index exists
721 * Usually aborts on failure
722 * If errors are explicitly ignored, returns NULL on failure
723 */
724 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
725 $info = $this->indexInfo( $table, $index, $fname );
726 if ( is_null( $info ) ) {
727 return NULL;
728 } else {
729 return $info !== false;
730 }
731 }
732
733
734 /**
735 * Get information about an index into an object
736 * Returns false if the index does not exist
737 */
738 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
739 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
740 # SHOW INDEX should work for 3.x and up:
741 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
742 $table = $this->tableName( $table );
743 $sql = 'SHOW INDEX FROM '.$table;
744 $res = $this->query( $sql, $fname );
745 if ( !$res ) {
746 return NULL;
747 }
748
749 while ( $row = $this->fetchObject( $res ) ) {
750 if ( $row->Key_name == $index ) {
751 return $row;
752 }
753 }
754 return false;
755 }
756
757 /**
758 * Query whether a given table exists
759 */
760 function tableExists( $table ) {
761 $table = $this->tableName( $table );
762 $old = $this->ignoreErrors( true );
763 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
764 $this->ignoreErrors( $old );
765 if( $res ) {
766 $this->freeResult( $res );
767 return true;
768 } else {
769 return false;
770 }
771 }
772
773 /**
774 * mysql_fetch_field() wrapper
775 * Returns false if the field doesn't exist
776 *
777 * @param $table
778 * @param $field
779 */
780 function fieldInfo( $table, $field ) {
781 $table = $this->tableName( $table );
782 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
783 $n = mysql_num_fields( $res );
784 for( $i = 0; $i < $n; $i++ ) {
785 $meta = mysql_fetch_field( $res, $i );
786 if( $field == $meta->name ) {
787 return $meta;
788 }
789 }
790 return false;
791 }
792
793 /**
794 * mysql_field_type() wrapper
795 */
796 function fieldType( $res, $index ) {
797 return mysql_field_type( $res, $index );
798 }
799
800 /**
801 * Determines if a given index is unique
802 */
803 function indexUnique( $table, $index ) {
804 $indexInfo = $this->indexInfo( $table, $index );
805 if ( !$indexInfo ) {
806 return NULL;
807 }
808 return !$indexInfo->Non_unique;
809 }
810
811 /**
812 * INSERT wrapper, inserts an array into a table
813 *
814 * $a may be a single associative array, or an array of these with numeric keys, for
815 * multi-row insert.
816 *
817 * Usually aborts on failure
818 * If errors are explicitly ignored, returns success
819 */
820 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
821 # No rows to insert, easy just return now
822 if ( !count( $a ) ) {
823 return true;
824 }
825
826 $table = $this->tableName( $table );
827 if ( !is_array( $options ) ) {
828 $options = array( $options );
829 }
830 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
831 $multi = true;
832 $keys = array_keys( $a[0] );
833 } else {
834 $multi = false;
835 $keys = array_keys( $a );
836 }
837
838 $sql = 'INSERT ' . implode( ' ', $options ) .
839 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
840
841 if ( $multi ) {
842 $first = true;
843 foreach ( $a as $row ) {
844 if ( $first ) {
845 $first = false;
846 } else {
847 $sql .= ',';
848 }
849 $sql .= '(' . $this->makeList( $row ) . ')';
850 }
851 } else {
852 $sql .= '(' . $this->makeList( $a ) . ')';
853 }
854 return !!$this->query( $sql, $fname );
855 }
856
857 /**
858 * UPDATE wrapper, takes a condition array and a SET array
859 */
860 function update( $table, $values, $conds, $fname = 'Database::update' ) {
861 $table = $this->tableName( $table );
862 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
863 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
864 $this->query( $sql, $fname );
865 }
866
867 /**
868 * Makes a wfStrencoded list from an array
869 * $mode: LIST_COMMA - comma separated, no field names
870 * LIST_AND - ANDed WHERE clause (without the WHERE)
871 * LIST_SET - comma separated with field names, like a SET clause
872 * LIST_NAMES - comma separated field names
873 */
874 function makeList( $a, $mode = LIST_COMMA ) {
875 if ( !is_array( $a ) ) {
876 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
877 }
878
879 $first = true;
880 $list = '';
881 foreach ( $a as $field => $value ) {
882 if ( !$first ) {
883 if ( $mode == LIST_AND ) {
884 $list .= ' AND ';
885 } else {
886 $list .= ',';
887 }
888 } else {
889 $first = false;
890 }
891 if ( $mode == LIST_AND && is_numeric( $field ) ) {
892 $list .= "($value)";
893 } elseif ( $mode == LIST_AND && is_array ($value) ) {
894 $list .= $field." IN (".$this->makeList($value).") ";
895 } else {
896 if ( $mode == LIST_AND || $mode == LIST_SET ) {
897 $list .= $field.'=';
898 }
899 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
900 }
901 }
902 return $list;
903 }
904
905 /**
906 * Change the current database
907 */
908 function selectDB( $db ) {
909 $this->mDBname = $db;
910 return mysql_select_db( $db, $this->mConn );
911 }
912
913 /**
914 * Starts a timer which will kill the DB thread after $timeout seconds
915 */
916 function startTimer( $timeout ) {
917 global $IP;
918 if( function_exists( 'mysql_thread_id' ) ) {
919 # This will kill the query if it's still running after $timeout seconds.
920 $tid = mysql_thread_id( $this->mConn );
921 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
922 }
923 }
924
925 /**
926 * Stop a timer started by startTimer()
927 * Currently unimplemented.
928 *
929 */
930 function stopTimer() { }
931
932 /**
933 * Format a table name ready for use in constructing an SQL query
934 *
935 * This does two important things: it quotes table names which as necessary,
936 * and it adds a table prefix if there is one.
937 *
938 * All functions of this object which require a table name call this function
939 * themselves. Pass the canonical name to such functions. This is only needed
940 * when calling query() directly.
941 *
942 * @param string $name database table name
943 */
944 function tableName( $name ) {
945 global $wgSharedDB;
946 if ( $this->mTablePrefix !== '' ) {
947 if ( strpos( '.', $name ) === false ) {
948 $name = $this->mTablePrefix . $name;
949 }
950 }
951 if ( isset( $wgSharedDB ) && 'user' == $name ) {
952 $name = $wgSharedDB . '.' . $name;
953 }
954 return $name;
955 }
956
957 /**
958 * Fetch a number of table names into an array
959 * This is handy when you need to construct SQL for joins
960 *
961 * Example:
962 * extract($dbr->tableNames('user','watchlist'));
963 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
964 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
965 */
966 function tableNames() {
967 $inArray = func_get_args();
968 $retVal = array();
969 foreach ( $inArray as $name ) {
970 $retVal[$name] = $this->tableName( $name );
971 }
972 return $retVal;
973 }
974
975 /**
976 * Wrapper for addslashes()
977 * @param string $s String to be slashed.
978 * @return string slashed string.
979 */
980 function strencode( $s ) {
981 return addslashes( $s );
982 }
983
984 /**
985 * If it's a string, adds quotes and backslashes
986 * Otherwise returns as-is
987 */
988 function addQuotes( $s ) {
989 if ( is_null( $s ) ) {
990 $s = 'NULL';
991 } else {
992 # This will also quote numeric values. This should be harmless,
993 # and protects against weird problems that occur when they really
994 # _are_ strings such as article titles and string->number->string
995 # conversion is not 1:1.
996 $s = "'" . $this->strencode( $s ) . "'";
997 }
998 return $s;
999 }
1000
1001 /**
1002 * Returns an appropriately quoted sequence value for inserting a new row.
1003 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1004 * subclass will return an integer, and save the value for insertId()
1005 */
1006 function nextSequenceValue( $seqName ) {
1007 return NULL;
1008 }
1009
1010 /**
1011 * USE INDEX clause
1012 * PostgreSQL doesn't have them and returns ""
1013 */
1014 function useIndexClause( $index ) {
1015 return 'USE INDEX ('.$index.')';
1016 }
1017
1018 /**
1019 * REPLACE query wrapper
1020 * PostgreSQL simulates this with a DELETE followed by INSERT
1021 * $row is the row to insert, an associative array
1022 * $uniqueIndexes is an array of indexes. Each element may be either a
1023 * field name or an array of field names
1024 *
1025 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1026 * However if you do this, you run the risk of encountering errors which wouldn't have
1027 * occurred in MySQL
1028 *
1029 * @todo migrate comment to phodocumentor format
1030 */
1031 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1032 $table = $this->tableName( $table );
1033
1034 # Single row case
1035 if ( !is_array( reset( $rows ) ) ) {
1036 $rows = array( $rows );
1037 }
1038
1039 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1040 $first = true;
1041 foreach ( $rows as $row ) {
1042 if ( $first ) {
1043 $first = false;
1044 } else {
1045 $sql .= ',';
1046 }
1047 $sql .= '(' . $this->makeList( $row ) . ')';
1048 }
1049 return $this->query( $sql, $fname );
1050 }
1051
1052 /**
1053 * DELETE where the condition is a join
1054 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1055 *
1056 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1057 * join condition matches, set $conds='*'
1058 *
1059 * DO NOT put the join condition in $conds
1060 *
1061 * @param string $delTable The table to delete from.
1062 * @param string $joinTable The other table.
1063 * @param string $delVar The variable to join on, in the first table.
1064 * @param string $joinVar The variable to join on, in the second table.
1065 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1066 */
1067 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1068 if ( !$conds ) {
1069 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1070 }
1071
1072 $delTable = $this->tableName( $delTable );
1073 $joinTable = $this->tableName( $joinTable );
1074 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1075 if ( $conds != '*' ) {
1076 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1077 }
1078
1079 return $this->query( $sql, $fname );
1080 }
1081
1082 /**
1083 * Returns the size of a text field, or -1 for "unlimited"
1084 */
1085 function textFieldSize( $table, $field ) {
1086 $table = $this->tableName( $table );
1087 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1088 $res = $this->query( $sql, 'Database::textFieldSize' );
1089 $row = $this->fetchObject( $res );
1090 $this->freeResult( $res );
1091
1092 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1093 $size = $m[1];
1094 } else {
1095 $size = -1;
1096 }
1097 return $size;
1098 }
1099
1100 /**
1101 * @return string Always return 'LOW_PRIORITY'
1102 */
1103 function lowPriorityOption() {
1104 return 'LOW_PRIORITY';
1105 }
1106
1107 /**
1108 * DELETE query wrapper
1109 *
1110 * Use $conds == "*" to delete all rows
1111 */
1112 function delete( $table, $conds, $fname = 'Database::delete' ) {
1113 if ( !$conds ) {
1114 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1115 }
1116 $table = $this->tableName( $table );
1117 $sql = "DELETE FROM $table ";
1118 if ( $conds != '*' ) {
1119 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1120 }
1121 return $this->query( $sql, $fname );
1122 }
1123
1124 /**
1125 * INSERT SELECT wrapper
1126 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1127 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1128 * $conds may be "*" to copy the whole table
1129 */
1130 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1131 $destTable = $this->tableName( $destTable );
1132 $srcTable = $this->tableName( $srcTable );
1133 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1134 ' SELECT ' . implode( ',', $varMap ) .
1135 " FROM $srcTable";
1136 if ( $conds != '*' ) {
1137 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1138 }
1139 return $this->query( $sql, $fname );
1140 }
1141
1142 /**
1143 * Construct a LIMIT query with optional offset
1144 * This is used for query pages
1145 */
1146 function limitResult($limit,$offset) {
1147 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1148 }
1149
1150 /**
1151 * Returns an SQL expression for a simple conditional.
1152 * Uses IF on MySQL.
1153 *
1154 * @param string $cond SQL expression which will result in a boolean value
1155 * @param string $trueVal SQL expression to return if true
1156 * @param string $falseVal SQL expression to return if false
1157 * @return string SQL fragment
1158 */
1159 function conditional( $cond, $trueVal, $falseVal ) {
1160 return " IF($cond, $trueVal, $falseVal) ";
1161 }
1162
1163 /**
1164 * Determines if the last failure was due to a deadlock
1165 */
1166 function wasDeadlock() {
1167 return $this->lastErrno() == 1213;
1168 }
1169
1170 /**
1171 * Perform a deadlock-prone transaction.
1172 *
1173 * This function invokes a callback function to perform a set of write
1174 * queries. If a deadlock occurs during the processing, the transaction
1175 * will be rolled back and the callback function will be called again.
1176 *
1177 * Usage:
1178 * $dbw->deadlockLoop( callback, ... );
1179 *
1180 * Extra arguments are passed through to the specified callback function.
1181 *
1182 * Returns whatever the callback function returned on its successful,
1183 * iteration, or false on error, for example if the retry limit was
1184 * reached.
1185 */
1186 function deadlockLoop() {
1187 $myFname = 'Database::deadlockLoop';
1188
1189 $this->query( 'BEGIN', $myFname );
1190 $args = func_get_args();
1191 $function = array_shift( $args );
1192 $oldIgnore = $dbw->ignoreErrors( true );
1193 $tries = DEADLOCK_TRIES;
1194 if ( is_array( $function ) ) {
1195 $fname = $function[0];
1196 } else {
1197 $fname = $function;
1198 }
1199 do {
1200 $retVal = call_user_func_array( $function, $args );
1201 $error = $this->lastError();
1202 $errno = $this->lastErrno();
1203 $sql = $this->lastQuery();
1204
1205 if ( $errno ) {
1206 if ( $dbw->wasDeadlock() ) {
1207 # Retry
1208 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1209 } else {
1210 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1211 }
1212 }
1213 } while( $dbw->wasDeadlock && --$tries > 0 );
1214 $this->ignoreErrors( $oldIgnore );
1215 if ( $tries <= 0 ) {
1216 $this->query( 'ROLLBACK', $myFname );
1217 $this->reportQueryError( $error, $errno, $sql, $fname );
1218 return false;
1219 } else {
1220 $this->query( 'COMMIT', $myFname );
1221 return $retVal;
1222 }
1223 }
1224
1225 /**
1226 * Do a SELECT MASTER_POS_WAIT()
1227 *
1228 * @param string $file the binlog file
1229 * @param string $pos the binlog position
1230 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1231 */
1232 function masterPosWait( $file, $pos, $timeout ) {
1233 $encFile = $this->strencode( $file );
1234 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1235 $res = $this->query( $sql, 'Database::masterPosWait' );
1236 if ( $res && $row = $this->fetchRow( $res ) ) {
1237 $this->freeResult( $res );
1238 return $row[0];
1239 } else {
1240 return false;
1241 }
1242 }
1243
1244 /**
1245 * Get the position of the master from SHOW SLAVE STATUS
1246 */
1247 function getSlavePos() {
1248 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1249 $row = $this->fetchObject( $res );
1250 if ( $row ) {
1251 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1252 } else {
1253 return array( false, false );
1254 }
1255 }
1256
1257 /**
1258 * Get the position of the master from SHOW MASTER STATUS
1259 */
1260 function getMasterPos() {
1261 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1262 $row = $this->fetchObject( $res );
1263 if ( $row ) {
1264 return array( $row->File, $row->Position );
1265 } else {
1266 return array( false, false );
1267 }
1268 }
1269
1270 /**
1271 * Begin a transaction, or if a transaction has already started, continue it
1272 */
1273 function begin( $fname = 'Database::begin' ) {
1274 if ( !$this->mTrxLevel ) {
1275 $this->immediateBegin( $fname );
1276 } else {
1277 $this->mTrxLevel++;
1278 }
1279 }
1280
1281 /**
1282 * End a transaction, or decrement the nest level if transactions are nested
1283 */
1284 function commit( $fname = 'Database::commit' ) {
1285 if ( $this->mTrxLevel ) {
1286 $this->mTrxLevel--;
1287 }
1288 if ( !$this->mTrxLevel ) {
1289 $this->immediateCommit( $fname );
1290 }
1291 }
1292
1293 /**
1294 * Rollback a transaction
1295 */
1296 function rollback( $fname = 'Database::rollback' ) {
1297 $this->query( 'ROLLBACK', $fname );
1298 $this->mTrxLevel = 0;
1299 }
1300
1301 /**
1302 * Begin a transaction, committing any previously open transaction
1303 */
1304 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1305 $this->query( 'BEGIN', $fname );
1306 $this->mTrxLevel = 1;
1307 }
1308
1309 /**
1310 * Commit transaction, if one is open
1311 */
1312 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1313 $this->query( 'COMMIT', $fname );
1314 $this->mTrxLevel = 0;
1315 }
1316
1317 /**
1318 * Return MW-style timestamp used for MySQL schema
1319 */
1320 function timestamp( $ts=0 ) {
1321 return wfTimestamp(TS_MW,$ts);
1322 }
1323
1324 /**
1325 * @todo document
1326 */
1327 function &resultObject( &$result ) {
1328 if( empty( $result ) ) {
1329 return NULL;
1330 } else {
1331 return new ResultWrapper( $this, $result );
1332 }
1333 }
1334
1335 /**
1336 * Return aggregated value alias
1337 */
1338 function aggregateValue ($valuedata,$valuename='value') {
1339 return $valuename;
1340 }
1341
1342 /**
1343 * @return string wikitext of a link to the server software's web site
1344 */
1345 function getSoftwareLink() {
1346 return "[http://www.mysql.com/ MySQL]";
1347 }
1348
1349 /**
1350 * @return string Version information from the database
1351 */
1352 function getServerVersion() {
1353 return mysql_get_server_info();
1354 }
1355 }
1356
1357 /**
1358 * Database abstraction object for mySQL
1359 * Inherit all methods and properties of Database::Database()
1360 *
1361 * @package MediaWiki
1362 * @see Database
1363 * @version # $Id$
1364 */
1365 class DatabaseMysql extends Database {
1366 # Inherit all
1367 }
1368
1369
1370 /**
1371 * Result wrapper for grabbing data queried by someone else
1372 *
1373 * @package MediaWiki
1374 * @version # $Id$
1375 */
1376 class ResultWrapper {
1377 var $db, $result;
1378
1379 /**
1380 * @todo document
1381 */
1382 function ResultWrapper( $database, $result ) {
1383 $this->db =& $database;
1384 $this->result =& $result;
1385 }
1386
1387 /**
1388 * @todo document
1389 */
1390 function numRows() {
1391 return $this->db->numRows( $this->result );
1392 }
1393
1394 /**
1395 * @todo document
1396 */
1397 function &fetchObject() {
1398 return $this->db->fetchObject( $this->result );
1399 }
1400
1401 /**
1402 * @todo document
1403 */
1404 function &fetchRow() {
1405 return $this->db->fetchRow( $this->result );
1406 }
1407
1408 /**
1409 * @todo document
1410 */
1411 function free() {
1412 $this->db->freeResult( $this->result );
1413 unset( $this->result );
1414 unset( $this->db );
1415 }
1416 }
1417
1418 #------------------------------------------------------------------------------
1419 # Global functions
1420 #------------------------------------------------------------------------------
1421
1422 /**
1423 * Standard fail function, called by default when a connection cannot be
1424 * established.
1425 * Displays the file cache if possible
1426 */
1427 function wfEmergencyAbort( &$conn, $error ) {
1428 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1429
1430 if( !headers_sent() ) {
1431 header( 'HTTP/1.0 500 Internal Server Error' );
1432 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1433 /* Don't cache error pages! They cause no end of trouble... */
1434 header( 'Cache-control: none' );
1435 header( 'Pragma: nocache' );
1436 }
1437 $msg = $wgSiteNotice;
1438 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1439 $text = $msg;
1440
1441 if($wgUseFileCache) {
1442 if($wgTitle) {
1443 $t =& $wgTitle;
1444 } else {
1445 if($title) {
1446 $t = Title::newFromURL( $title );
1447 } elseif (@/**/$_REQUEST['search']) {
1448 $search = $_REQUEST['search'];
1449 echo wfMsgNoDB( 'searchdisabled' );
1450 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1451 wfErrorExit();
1452 } else {
1453 $t = Title::newFromText( wfMsgNoDBForContent( 'mainpage' ) );
1454 }
1455 }
1456
1457 $cache = new CacheManager( $t );
1458 if( $cache->isFileCached() ) {
1459 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1460 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1461
1462 $tag = '<div id="article">';
1463 $text = str_replace(
1464 $tag,
1465 $tag . $msg,
1466 $cache->fetchPageText() );
1467 }
1468 }
1469
1470 echo $text;
1471 wfErrorExit();
1472 }
1473
1474 ?>