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