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