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