Now it is straightforward to fix bug 89, subst: template parameters.
[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 * @param mixed $res A SQL result
357 */
358 /**
359 * @todo document
360 */
361 function freeResult( $res ) {
362 if ( !@/**/mysql_free_result( $res ) ) {
363 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
364 }
365 }
366
367 /**
368 * @todo FIXME: HACK HACK HACK HACK debug
369 */
370 function fetchObject( $res ) {
371 @/**/$row = mysql_fetch_object( $res );
372 # FIXME: HACK HACK HACK HACK debug
373 if( mysql_errno() ) {
374 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
375 }
376 return $row;
377 }
378
379 /**
380 * @todo document
381 */
382 function fetchRow( $res ) {
383 @/**/$row = mysql_fetch_array( $res );
384 if (mysql_errno() ) {
385 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
386 }
387 return $row;
388 }
389
390 /**
391 * @todo document
392 */
393 function numRows( $res ) {
394 @/**/$n = mysql_num_rows( $res );
395 if( mysql_errno() ) {
396 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
397 }
398 return $n;
399 }
400
401 /**
402 * @todo document
403 */
404 function numFields( $res ) { return mysql_num_fields( $res ); }
405
406 /**
407 * @todo document
408 */
409 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
410 /**
411 * @todo document
412 */
413 function insertId() { return mysql_insert_id( $this->mConn ); }
414 /**
415 * @todo document
416 */
417 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
418 /**
419 * @todo document
420 */
421 function lastErrno() { return mysql_errno(); }
422 /**
423 * @todo document
424 */
425 function lastError() { return mysql_error(); }
426 /**
427 * @todo document
428 */
429 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
430 /**#@-*/ // end of template : @param $result
431
432 /**
433 * Simple UPDATE wrapper
434 * Usually aborts on failure
435 * If errors are explicitly ignored, returns success
436 *
437 * This function exists for historical reasons, Database::update() has a more standard
438 * calling convention and feature set
439 */
440 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
441 {
442 $table = $this->tableName( $table );
443 $sql = "UPDATE $table SET $var = '" .
444 $this->strencode( $value ) . "' WHERE ($cond)";
445 return !!$this->query( $sql, DB_MASTER, $fname );
446 }
447
448 /**
449 * @todo document
450 */
451 function getField( $table, $var, $cond='', $fname = 'Database::getField', $options = array() ) {
452 return $this->selectField( $table, $var, $cond, $fname = 'Database::get', $options = array() );
453 }
454
455 /**
456 * Simple SELECT wrapper, returns a single field, input must be encoded
457 * Usually aborts on failure
458 * If errors are explicitly ignored, returns FALSE on failure
459 */
460 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
461 if ( !is_array( $options ) ) {
462 $options = array( $options );
463 }
464 $options['LIMIT'] = 1;
465
466 $res = $this->select( $table, $var, $cond, $fname, $options );
467 if ( $res === false || !$this->numRows( $res ) ) {
468 return false;
469 }
470 $row = $this->fetchRow( $res );
471 if ( $row !== false ) {
472 $this->freeResult( $res );
473 return $row[0];
474 } else {
475 return false;
476 }
477 }
478
479 /**
480 * Returns an optional USE INDEX clause to go after the table, and a
481 * string to go at the end of the query
482 */
483 function makeSelectOptions( $options ) {
484 if ( !is_array( $options ) ) {
485 $options = array( $options );
486 }
487
488 $tailOpts = '';
489
490 if ( isset( $options['ORDER BY'] ) ) {
491 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
492 }
493 if ( isset( $options['LIMIT'] ) ) {
494 $tailOpts .= " LIMIT {$options['LIMIT']}";
495 }
496
497 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
498 $tailOpts .= ' FOR UPDATE';
499 }
500
501 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
502 $tailOpts .= ' LOCK IN SHARE MODE';
503 }
504
505 if ( isset( $options['USE INDEX'] ) ) {
506 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
507 } else {
508 $useIndex = '';
509 }
510 return array( $useIndex, $tailOpts );
511 }
512
513 /**
514 * SELECT wrapper
515 */
516 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
517 {
518 if ( is_array( $vars ) ) {
519 $vars = implode( ',', $vars );
520 }
521 if ($table!='')
522 $from = ' FROM ' .$this->tableName( $table );
523 else
524 $from = '';
525
526 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
527
528 if ( $conds !== false && $conds != '' ) {
529 if ( is_array( $conds ) ) {
530 $conds = $this->makeList( $conds, LIST_AND );
531 }
532 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
533 } else {
534 $sql = "SELECT $vars $from $useIndex $tailOpts";
535 }
536 return $this->query( $sql, $fname );
537 }
538
539 /**
540 * @todo document
541 */
542 function getArray( $table, $vars, $conds, $fname = 'Database::getArray', $options = array() ) {
543 return $this->selectRow( $table, $vars, $conds, $fname, $options );
544 }
545
546
547 /**
548 * Single row SELECT wrapper
549 * Aborts or returns FALSE on error
550 *
551 * $vars: the selected variables
552 * $conds: a condition map, terms are ANDed together.
553 * Items with numeric keys are taken to be literal conditions
554 * Takes an array of selected variables, and a condition map, which is ANDed
555 * e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
556 * would return an object where $obj->cur_id is the ID of the Astronomy article
557 *
558 * @todo migrate documentation to phpdocumentor format
559 */
560 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
561 $options['LIMIT'] = 1;
562 $res = $this->select( $table, $vars, $conds, $fname, $options );
563 if ( $res === false || !$this->numRows( $res ) ) {
564 return false;
565 }
566 $obj = $this->fetchObject( $res );
567 $this->freeResult( $res );
568 return $obj;
569
570 }
571
572 /**
573 * Removes most variables from an SQL query and replaces them with X or N for numbers.
574 * It's only slightly flawed. Don't use for anything important.
575 *
576 * @param string $sql A SQL Query
577 * @static
578 */
579 function generalizeSQL( $sql ) {
580 # This does the same as the regexp below would do, but in such a way
581 # as to avoid crashing php on some large strings.
582 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
583
584 $sql = str_replace ( "\\\\", '', $sql);
585 $sql = str_replace ( "\\'", '', $sql);
586 $sql = str_replace ( "\\\"", '', $sql);
587 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
588 $sql = preg_replace ('/".*"/s', "'X'", $sql);
589
590 # All newlines, tabs, etc replaced by single space
591 $sql = preg_replace ( "/\s+/", ' ', $sql);
592
593 # All numbers => N
594 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
595
596 return $sql;
597 }
598
599 /**
600 * Determines whether a field exists in a table
601 * Usually aborts on failure
602 * If errors are explicitly ignored, returns NULL on failure
603 */
604 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
605 $table = $this->tableName( $table );
606 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
607 if ( !$res ) {
608 return NULL;
609 }
610
611 $found = false;
612
613 while ( $row = $this->fetchObject( $res ) ) {
614 if ( $row->Field == $field ) {
615 $found = true;
616 break;
617 }
618 }
619 return $found;
620 }
621
622 /**
623 * Determines whether an index exists
624 * Usually aborts on failure
625 * If errors are explicitly ignored, returns NULL on failure
626 */
627 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
628 $info = $this->indexInfo( $table, $index, $fname );
629 if ( is_null( $info ) ) {
630 return NULL;
631 } else {
632 return $info !== false;
633 }
634 }
635
636
637 /**
638 * @todo document
639 */
640 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
641 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
642 # SHOW INDEX should work for 3.x and up:
643 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
644 $table = $this->tableName( $table );
645 $sql = 'SHOW INDEX FROM '.$table;
646 $res = $this->query( $sql, $fname );
647 if ( !$res ) {
648 return NULL;
649 }
650
651 while ( $row = $this->fetchObject( $res ) ) {
652 if ( $row->Key_name == $index ) {
653 return $row;
654 }
655 }
656 return false;
657 }
658
659 /**
660 * @param $table
661 * @todo document
662 */
663 function tableExists( $table ) {
664 $table = $this->tableName( $table );
665 $old = $this->ignoreErrors( true );
666 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
667 $this->ignoreErrors( $old );
668 if( $res ) {
669 $this->freeResult( $res );
670 return true;
671 } else {
672 return false;
673 }
674 }
675
676 /**
677 * @param $table
678 * @param $field
679 * @todo document
680 */
681 function fieldInfo( $table, $field ) {
682 $table = $this->tableName( $table );
683 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
684 $n = mysql_num_fields( $res );
685 for( $i = 0; $i < $n; $i++ ) {
686 $meta = mysql_fetch_field( $res, $i );
687 if( $field == $meta->name ) {
688 return $meta;
689 }
690 }
691 return false;
692 }
693
694 /**
695 * @todo document
696 */
697 function fieldType( $res, $index ) {
698 return mysql_field_type( $res, $index );
699 }
700
701 /**
702 * @todo document
703 */
704 function indexUnique( $table, $index ) {
705 $indexInfo = $this->indexInfo( $table, $index );
706 if ( !$indexInfo ) {
707 return NULL;
708 }
709 return !$indexInfo->Non_unique;
710 }
711
712 /**
713 * @todo document
714 */
715 function insertArray( $table, $a, $fname = 'Database::insertArray', $options = array() ) {
716 return $this->insert( $table, $a, $fname = 'Database::insertArray', $options = array() );
717 }
718
719 /**
720 * INSERT wrapper, inserts an array into a table
721 *
722 * $a may be a single associative array, or an array of these with numeric keys, for
723 * multi-row insert.
724 *
725 * Usually aborts on failure
726 * If errors are explicitly ignored, returns success
727 */
728 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
729 # No rows to insert, easy just return now
730 if ( !count( $a ) ) {
731 return true;
732 }
733
734 $table = $this->tableName( $table );
735 if ( !is_array( $options ) ) {
736 $options = array( $options );
737 }
738 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
739 $multi = true;
740 $keys = array_keys( $a[0] );
741 } else {
742 $multi = false;
743 $keys = array_keys( $a );
744 }
745
746 $sql = 'INSERT ' . implode( ' ', $options ) .
747 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
748
749 if ( $multi ) {
750 $first = true;
751 foreach ( $a as $row ) {
752 if ( $first ) {
753 $first = false;
754 } else {
755 $sql .= ',';
756 }
757 $sql .= '(' . $this->makeList( $row ) . ')';
758 }
759 } else {
760 $sql .= '(' . $this->makeList( $a ) . ')';
761 }
762 return !!$this->query( $sql, $fname );
763 }
764
765 /**
766 * @todo document
767 */
768 function updateArray( $table, $values, $conds, $fname = 'Database::updateArray' ) {
769 return $this->update( $table, $values, $conds, $fname );
770 }
771
772 /**
773 * UPDATE wrapper, takes a condition array and a SET array
774 */
775 function update( $table, $values, $conds, $fname = 'Database::update' ) {
776 $table = $this->tableName( $table );
777 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
778 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
779 $this->query( $sql, $fname );
780 }
781
782 /**
783 * Makes a wfStrencoded list from an array
784 * $mode: LIST_COMMA - comma separated, no field names
785 * LIST_AND - ANDed WHERE clause (without the WHERE)
786 * LIST_SET - comma separated with field names, like a SET clause
787 * LIST_NAMES - comma separated field names
788 */
789 function makeList( $a, $mode = LIST_COMMA ) {
790 if ( !is_array( $a ) ) {
791 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
792 }
793
794 $first = true;
795 $list = '';
796 foreach ( $a as $field => $value ) {
797 if ( !$first ) {
798 if ( $mode == LIST_AND ) {
799 $list .= ' AND ';
800 } else {
801 $list .= ',';
802 }
803 } else {
804 $first = false;
805 }
806 if ( $mode == LIST_AND && is_numeric( $field ) ) {
807 $list .= "($value)";
808 } else {
809 if ( $mode == LIST_AND || $mode == LIST_SET ) {
810 $list .= $field.'=';
811 }
812 $list .= ($mode==LIST_NAMES?$value:$this->addQuotes( $value ));
813 }
814 }
815 return $list;
816 }
817
818 /**
819 * @todo document
820 */
821 function selectDB( $db ) {
822 $this->mDBname = $db;
823 return mysql_select_db( $db, $this->mConn );
824 }
825
826 /**
827 * @todo document
828 */
829 function startTimer( $timeout ) {
830 global $IP;
831 if( function_exists( 'mysql_thread_id' ) ) {
832 # This will kill the query if it's still running after $timeout seconds.
833 $tid = mysql_thread_id( $this->mConn );
834 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
835 }
836 }
837
838 /**
839 * Does nothing at all
840 * @todo document
841 */
842 function stopTimer() { }
843
844 /**
845 * @param string $name database table name
846 * @todo document
847 */
848 function tableName( $name ) {
849 global $wgSharedDB;
850 if ( $this->mTablePrefix !== '' ) {
851 if ( strpos( '.', $name ) === false ) {
852 $name = $this->mTablePrefix . $name;
853 }
854 }
855 if ( isset( $wgSharedDB ) && 'user' == $name ) {
856 $name = $wgSharedDB . '.' . $name;
857 }
858 return $name;
859 }
860
861 /**
862 * @todo document
863 */
864 function tableNames() {
865 $inArray = func_get_args();
866 $retVal = array();
867 foreach ( $inArray as $name ) {
868 $retVal[$name] = $this->tableName( $name );
869 }
870 return $retVal;
871 }
872
873 /**
874 * Wrapper for addslashes()
875 * @param string $s String to be slashed.
876 * @return string slashed string.
877 */
878 function strencode( $s ) {
879 return addslashes( $s );
880 }
881
882 /**
883 * If it's a string, adds quotes and backslashes
884 * Otherwise returns as-is
885 */
886 function addQuotes( $s ) {
887 if ( is_null( $s ) ) {
888 $s = 'NULL';
889 } else {
890 # This will also quote numeric values. This should be harmless,
891 # and protects against weird problems that occur when they really
892 # _are_ strings such as article titles and string->number->string
893 # conversion is not 1:1.
894 $s = "'" . $this->strencode( $s ) . "'";
895 }
896 return $s;
897 }
898
899 /**
900 * Returns an appropriately quoted sequence value for inserting a new row.
901 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
902 * subclass will return an integer, and save the value for insertId()
903 */
904 function nextSequenceValue( $seqName ) {
905 return NULL;
906 }
907
908 /**
909 * USE INDEX clause
910 * PostgreSQL doesn't have them and returns ""
911 */
912 function useIndexClause( $index ) {
913 return 'USE INDEX ('.$index.')';
914 }
915
916 /**
917 * REPLACE query wrapper
918 * PostgreSQL simulates this with a DELETE followed by INSERT
919 * $row is the row to insert, an associative array
920 * $uniqueIndexes is an array of indexes. Each element may be either a
921 * field name or an array of field names
922 *
923 * It may be more efficient to leave off unique indexes which are unlikely to collide.
924 * However if you do this, you run the risk of encountering errors which wouldn't have
925 * occurred in MySQL
926 *
927 * @todo migrate comment to phodocumentor format
928 */
929 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
930 $table = $this->tableName( $table );
931
932 # Single row case
933 if ( !is_array( reset( $rows ) ) ) {
934 $rows = array( $rows );
935 }
936
937 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
938 $first = true;
939 foreach ( $rows as $row ) {
940 if ( $first ) {
941 $first = false;
942 } else {
943 $sql .= ',';
944 }
945 $sql .= '(' . $this->makeList( $row ) . ')';
946 }
947 return $this->query( $sql, $fname );
948 }
949
950 /**
951 * DELETE where the condition is a join
952 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
953 *
954 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
955 * join condition matches, set $conds='*'
956 *
957 * DO NOT put the join condition in $conds
958 *
959 * @param string $delTable The table to delete from.
960 * @param string $joinTable The other table.
961 * @param string $delVar The variable to join on, in the first table.
962 * @param string $joinVar The variable to join on, in the second table.
963 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
964 */
965 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
966 if ( !$conds ) {
967 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
968 }
969
970 $delTable = $this->tableName( $delTable );
971 $joinTable = $this->tableName( $joinTable );
972 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
973 if ( $conds != '*' ) {
974 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
975 }
976
977 return $this->query( $sql, $fname );
978 }
979
980 /**
981 * Returns the size of a text field, or -1 for "unlimited"
982 */
983 function textFieldSize( $table, $field ) {
984 $table = $this->tableName( $table );
985 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
986 $res = $this->query( $sql, 'Database::textFieldSize' );
987 $row = $this->fetchObject( $res );
988 $this->freeResult( $res );
989
990 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
991 $size = $m[1];
992 } else {
993 $size = -1;
994 }
995 return $size;
996 }
997
998 /**
999 * @return string Always return 'LOW_PRIORITY'
1000 */
1001 function lowPriorityOption() {
1002 return 'LOW_PRIORITY';
1003 }
1004
1005 /**
1006 * Use $conds == "*" to delete all rows
1007 * @todo document
1008 */
1009 function delete( $table, $conds, $fname = 'Database::delete' ) {
1010 if ( !$conds ) {
1011 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1012 }
1013 $table = $this->tableName( $table );
1014 $sql = "DELETE FROM $table ";
1015 if ( $conds != '*' ) {
1016 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
1017 }
1018 return $this->query( $sql, $fname );
1019 }
1020
1021 /**
1022 * INSERT SELECT wrapper
1023 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1024 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1025 * $conds may be "*" to copy the whole table
1026 */
1027 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1028 $destTable = $this->tableName( $destTable );
1029 $srcTable = $this->tableName( $srcTable );
1030 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1031 ' SELECT ' . implode( ',', $varMap ) .
1032 " FROM $srcTable";
1033 if ( $conds != '*' ) {
1034 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1035 }
1036 return $this->query( $sql, $fname );
1037 }
1038
1039 /**
1040 * @todo document
1041 */
1042 function limitResult($limit,$offset) {
1043 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1044 }
1045
1046 /**
1047 * Returns an SQL expression for a simple conditional.
1048 * Uses IF on MySQL.
1049 *
1050 * @param string $cond SQL expression which will result in a boolean value
1051 * @param string $trueVal SQL expression to return if true
1052 * @param string $falseVal SQL expression to return if false
1053 * @return string SQL fragment
1054 */
1055 function conditional( $cond, $trueVal, $falseVal ) {
1056 return " IF($cond, $trueVal, $falseVal) ";
1057 }
1058
1059 /**
1060 * @todo document
1061 */
1062 function wasDeadlock() {
1063 return $this->lastErrno() == 1213;
1064 }
1065
1066 /**
1067 * @todo document
1068 */
1069 function deadlockLoop() {
1070 $myFname = 'Database::deadlockLoop';
1071
1072 $this->query( 'BEGIN', $myFname );
1073 $args = func_get_args();
1074 $function = array_shift( $args );
1075 $oldIgnore = $dbw->ignoreErrors( true );
1076 $tries = DEADLOCK_TRIES;
1077 if ( is_array( $function ) ) {
1078 $fname = $function[0];
1079 } else {
1080 $fname = $function;
1081 }
1082 do {
1083 $retVal = call_user_func_array( $function, $args );
1084 $error = $this->lastError();
1085 $errno = $this->lastErrno();
1086 $sql = $this->lastQuery();
1087
1088 if ( $errno ) {
1089 if ( $dbw->wasDeadlock() ) {
1090 # Retry
1091 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1092 } else {
1093 $dbw->reportQueryError( $error, $errno, $sql, $fname );
1094 }
1095 }
1096 } while( $dbw->wasDeadlock && --$tries > 0 );
1097 $this->ignoreErrors( $oldIgnore );
1098 if ( $tries <= 0 ) {
1099 $this->query( 'ROLLBACK', $myFname );
1100 $this->reportQueryError( $error, $errno, $sql, $fname );
1101 return false;
1102 } else {
1103 $this->query( 'COMMIT', $myFname );
1104 return $retVal;
1105 }
1106 }
1107
1108 /**
1109 * Do a SELECT MASTER_POS_WAIT()
1110 * @todo document
1111 */
1112 function masterPosWait( $file, $pos, $timeout ) {
1113 $encFile = $this->strencode( $file );
1114 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1115 $res = $this->query( $sql, 'Database::masterPosWait' );
1116 if ( $res && $row = $this->fetchRow( $res ) ) {
1117 $this->freeResult( $res );
1118 return $row[0];
1119 } else {
1120 return false;
1121 }
1122 }
1123
1124 /**
1125 * Get the position of the master from SHOW SLAVE STATUS
1126 */
1127 function getSlavePos() {
1128 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1129 $row = $this->fetchObject( $res );
1130 if ( $row ) {
1131 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1132 } else {
1133 return array( false, false );
1134 }
1135 }
1136
1137 /**
1138 * Get the position of the master from SHOW MASTER STATUS
1139 */
1140 function getMasterPos() {
1141 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1142 $row = $this->fetchObject( $res );
1143 if ( $row ) {
1144 return array( $row->File, $row->Position );
1145 } else {
1146 return array( false, false );
1147 }
1148 }
1149
1150 /**
1151 * Begin a transaction, or if a transaction has already started, continue it
1152 */
1153 function begin( $fname = 'Database::begin' ) {
1154 if ( !$this->mTrxLevel ) {
1155 $this->immediateBegin( $fname );
1156 } else {
1157 $this->mTrxLevel++;
1158 }
1159 }
1160
1161 /**
1162 * End a transaction, or decrement the nest level if transactions are nested
1163 */
1164 function commit( $fname = 'Database::commit' ) {
1165 if ( $this->mTrxLevel ) {
1166 $this->mTrxLevel--;
1167 }
1168 if ( !$this->mTrxLevel ) {
1169 $this->immediateCommit( $fname );
1170 }
1171 }
1172
1173 /**
1174 * Rollback a transaction
1175 */
1176 function rollback( $fname = 'Database::rollback' ) {
1177 $this->query( 'ROLLBACK', $fname );
1178 $this->mTrxLevel = 0;
1179 }
1180
1181 /**
1182 * Begin a transaction, committing any previously open transaction
1183 */
1184 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1185 $this->query( 'BEGIN', $fname );
1186 $this->mTrxLevel = 1;
1187 }
1188
1189 /**
1190 * Commit transaction, if one is open
1191 */
1192 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1193 $this->query( 'COMMIT', $fname );
1194 $this->mTrxLevel = 0;
1195 }
1196
1197 /**
1198 * Return MW-style timestamp used for MySQL schema
1199 */
1200 function timestamp( $ts=0 ) {
1201 return wfTimestamp(TS_MW,$ts);
1202 }
1203
1204 /**
1205 * @todo document
1206 */
1207 function &resultObject( &$result ) {
1208 if( empty( $result ) ) {
1209 return NULL;
1210 } else {
1211 return new ResultWrapper( $this, $result );
1212 }
1213 }
1214
1215 /**
1216 * Return aggregated value alias
1217 */
1218 function aggregateValue ($valuedata,$valuename='value') {
1219 return $valuename;
1220 }
1221
1222 /**
1223 * @return string wikitext of a link to the server software's web site
1224 */
1225 function getSoftwareLink() {
1226 return "[http://www.mysql.com/ MySQL]";
1227 }
1228
1229 /**
1230 * @return string Version information from the database
1231 */
1232 function getServerVersion() {
1233 return mysql_get_server_info();
1234 }
1235 }
1236
1237 /**
1238 * Database abstraction object for mySQL
1239 * Inherit all methods and properties of Database::Database()
1240 *
1241 * @package MediaWiki
1242 * @see Database
1243 * @version # $Id$
1244 */
1245 class DatabaseMysql extends Database {
1246 # Inherit all
1247 }
1248
1249
1250 /**
1251 * Result wrapper for grabbing data queried by someone else
1252 *
1253 * @package MediaWiki
1254 * @version # $Id$
1255 */
1256 class ResultWrapper {
1257 var $db, $result;
1258
1259 /**
1260 * @todo document
1261 */
1262 function ResultWrapper( $database, $result ) {
1263 $this->db =& $database;
1264 $this->result =& $result;
1265 }
1266
1267 /**
1268 * @todo document
1269 */
1270 function numRows() {
1271 return $this->db->numRows( $this->result );
1272 }
1273
1274 /**
1275 * @todo document
1276 */
1277 function &fetchObject() {
1278 return $this->db->fetchObject( $this->result );
1279 }
1280
1281 /**
1282 * @todo document
1283 */
1284 function &fetchRow() {
1285 return $this->db->fetchRow( $this->result );
1286 }
1287
1288 /**
1289 * @todo document
1290 */
1291 function free() {
1292 $this->db->freeResult( $this->result );
1293 unset( $this->result );
1294 unset( $this->db );
1295 }
1296 }
1297
1298 #------------------------------------------------------------------------------
1299 # Global functions
1300 #------------------------------------------------------------------------------
1301
1302 /**
1303 * Standard fail function, called by default when a connection cannot be
1304 * established.
1305 * Displays the file cache if possible
1306 */
1307 function wfEmergencyAbort( &$conn, $error ) {
1308 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
1309
1310 if( !headers_sent() ) {
1311 header( 'HTTP/1.0 500 Internal Server Error' );
1312 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1313 /* Don't cache error pages! They cause no end of trouble... */
1314 header( 'Cache-control: none' );
1315 header( 'Pragma: nocache' );
1316 }
1317 $msg = $wgSiteNotice;
1318 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
1319 $text = $msg;
1320
1321 if($wgUseFileCache) {
1322 if($wgTitle) {
1323 $t =& $wgTitle;
1324 } else {
1325 if($title) {
1326 $t = Title::newFromURL( $title );
1327 } elseif (@/**/$_REQUEST['search']) {
1328 $search = $_REQUEST['search'];
1329 echo wfMsgNoDB( 'searchdisabled' );
1330 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
1331 wfErrorExit();
1332 } else {
1333 $t = Title::newFromText( wfMsgNoDB( 'mainpage' ) );
1334 }
1335 }
1336
1337 $cache = new CacheManager( $t );
1338 if( $cache->isFileCached() ) {
1339 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1340 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
1341
1342 $tag = '<div id="article">';
1343 $text = str_replace(
1344 $tag,
1345 $tag . $msg,
1346 $cache->fetchPageText() );
1347 }
1348 }
1349
1350 echo $text;
1351 wfErrorExit();
1352 }
1353
1354 ?>