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