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