acfab2bb90910606f813015ea8065a89bc0ad9b2
[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 if ( !is_numeric( $s ) ) {
700 $s = "'" . $this->strencode( $s ) . "'";
701 }
702 return $s;
703 }
704
705 # Returns an appropriately quoted sequence value for inserting a new row.
706 # MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
707 # subclass will return an integer, and save the value for insertId()
708 function nextSequenceValue( $seqName ) {
709 return NULL;
710 }
711
712 # USE INDEX clause
713 # PostgreSQL doesn't have them and returns ""
714 function useIndexClause( $index ) {
715 return 'USE INDEX ('.$index.')';
716 }
717
718 # REPLACE query wrapper
719 # PostgreSQL simulates this with a DELETE followed by INSERT
720 # $row is the row to insert, an associative array
721 # $uniqueIndexes is an array of indexes. Each element may be either a
722 # field name or an array of field names
723 #
724 # It may be more efficient to leave off unique indexes which are unlikely to collide.
725 # However if you do this, you run the risk of encountering errors which wouldn't have
726 # occurred in MySQL
727 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
728 $table = $this->tableName( $table );
729
730 # Single row case
731 if ( !is_array( reset( $rows ) ) ) {
732 $rows = array( $rows );
733 }
734
735 $sql = "REPLACE INTO $table (" . implode( ',', array_flip( $rows[0] ) ) .') VALUES ';
736 $first = true;
737 foreach ( $rows as $row ) {
738 if ( $first ) {
739 $first = false;
740 } else {
741 $sql .= ',';
742 }
743 $sql .= '(' . $this->makeList( $row ) . ')';
744 }
745 return $this->query( $sql, $fname );
746 }
747
748 # DELETE where the condition is a join
749 # MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
750 #
751 # $delTable is the table to delete from
752 # $joinTable is the other table
753 # $delVar is the variable to join on, in the first table
754 # $joinVar is the variable to join on, in the second table
755 # $conds is a condition array of field names mapped to variables, ANDed together in the WHERE clause
756 #
757 # For safety, an empty $conds will not delete everything. If you want to delete all rows where the
758 # join condition matches, set $conds='*'
759 #
760 # DO NOT put the join condition in $conds
761 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
762 if ( !$conds ) {
763 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
764 }
765
766 $delTable = $this->tableName( $delTable );
767 $joinTable = $this->tableName( $joinTable );
768 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
769 if ( $conds != '*' ) {
770 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
771 }
772
773 return $this->query( $sql, $fname );
774 }
775
776 # Returns the size of a text field, or -1 for "unlimited"
777 function textFieldSize( $table, $field ) {
778 $table = $this->tableName( $table );
779 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
780 $res = $this->query( $sql, 'Database::textFieldSize' );
781 $row = $this->fetchObject( $res );
782 $this->freeResult( $res );
783
784 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
785 $size = $m[1];
786 } else {
787 $size = -1;
788 }
789 return $size;
790 }
791
792 function lowPriorityOption() {
793 return 'LOW_PRIORITY';
794 }
795
796 # Use $conds == "*" to delete all rows
797 function delete( $table, $conds, $fname = 'Database::delete' ) {
798 if ( !$conds ) {
799 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
800 }
801 $table = $this->tableName( $table );
802 $sql = "DELETE FROM $table ";
803 if ( $conds != '*' ) {
804 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
805 }
806 return $this->query( $sql, $fname );
807 }
808
809 # INSERT SELECT wrapper
810 # $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
811 # Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
812 # $conds may be "*" to copy the whole table
813 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
814 $destTable = $this->tableName( $destTable );
815 $srcTable = $this->tableName( $srcTable );
816 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
817 ' SELECT ' . implode( ',', $varMap ) .
818 " FROM $srcTable";
819 if ( $conds != '*' ) {
820 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
821 }
822 return $this->query( $sql, $fname );
823 }
824
825 function limitResult($limit,$offset) {
826 return ' LIMIT '.(is_numeric($offset)?"{$offset},":"")."{$limit} ";
827 }
828
829 function wasDeadlock() {
830 return $this->lastErrno() == 1213;
831 }
832
833 function deadlockLoop() {
834 $myFname = 'Database::deadlockLoop';
835
836 $this->query( 'BEGIN', $myFname );
837 $args = func_get_args();
838 $function = array_shift( $args );
839 $oldIgnore = $dbw->ignoreErrors( true );
840 $tries = DEADLOCK_TRIES;
841 if ( is_array( $function ) ) {
842 $fname = $function[0];
843 } else {
844 $fname = $function;
845 }
846 do {
847 $retVal = call_user_func_array( $function, $args );
848 $error = $this->lastError();
849 $errno = $this->lastErrno();
850 $sql = $this->lastQuery();
851
852 if ( $errno ) {
853 if ( $dbw->wasDeadlock() ) {
854 # Retry
855 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
856 } else {
857 $dbw->reportQueryError( $error, $errno, $sql, $fname );
858 }
859 }
860 } while( $dbw->wasDeadlock && --$tries > 0 );
861 $this->ignoreErrors( $oldIgnore );
862 if ( $tries <= 0 ) {
863 $this->query( 'ROLLBACK', $myFname );
864 $this->reportQueryError( $error, $errno, $sql, $fname );
865 return false;
866 } else {
867 $this->query( 'COMMIT', $myFname );
868 return $retVal;
869 }
870 }
871
872 # Do a SELECT MASTER_POS_WAIT()
873 function masterPosWait( $file, $pos, $timeout ) {
874 $encFile = $this->strencode( $file );
875 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
876 $res = $this->query( $sql, 'Database::masterPosWait' );
877 if ( $res && $row = $this->fetchRow( $res ) ) {
878 $this->freeResult( $res );
879 return $row[0];
880 } else {
881 return false;
882 }
883 }
884
885 # Get the position of the master from SHOW SLAVE STATUS
886 function getSlavePos() {
887 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
888 $row = $this->fetchObject( $res );
889 if ( $row ) {
890 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
891 } else {
892 return array( false, false );
893 }
894 }
895
896 # Get the position of the master from SHOW MASTER STATUS
897 function getMasterPos() {
898 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
899 $row = $this->fetchObject( $res );
900 if ( $row ) {
901 return array( $row->File, $row->Position );
902 } else {
903 return array( false, false );
904 }
905 }
906
907 # Begin a transaction, or if a transaction has already started, continue it
908 function begin( $fname = 'Database::begin' ) {
909 if ( !$this->mTrxLevel ) {
910 $this->immediateBegin( $fname );
911 } else {
912 $this->mTrxLevel++;
913 }
914 }
915
916 # End a transaction, or decrement the nest level if transactions are nested
917 function commit( $fname = 'Database::commit' ) {
918 if ( $this->mTrxLevel ) {
919 $this->mTrxLevel--;
920 }
921 if ( !$this->mTrxLevel ) {
922 $this->immediateCommit( $fname );
923 }
924 }
925
926 # Rollback a transaction
927 function rollback( $fname = 'Database::rollback' ) {
928 $this->query( 'ROLLBACK', $fname );
929 $this->mTrxLevel = 0;
930 }
931
932 # Begin a transaction, committing any previously open transaction
933 function immediateBegin( $fname = 'Database::immediateBegin' ) {
934 $this->query( 'BEGIN', $fname );
935 $this->mTrxLevel = 1;
936 }
937
938 # Commit transaction, if one is open
939 function immediateCommit( $fname = 'Database::immediateCommit' ) {
940 $this->query( 'COMMIT', $fname );
941 $this->mTrxLevel = 0;
942 }
943
944 # Return MW-style timestamp used for MySQL schema
945 function timestamp( $ts=0 ) {
946 return wfTimestamp(TS_MW,$ts);
947 }
948 }
949
950 class DatabaseMysql extends Database {
951 # Inherit all
952 }
953
954 #------------------------------------------------------------------------------
955 # Global functions
956 #------------------------------------------------------------------------------
957
958 /* Standard fail function, called by default when a connection cannot be established
959 Displays the file cache if possible */
960 function wfEmergencyAbort( &$conn, $error ) {
961 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
962
963 if( !headers_sent() ) {
964 header( 'HTTP/1.0 500 Internal Server Error' );
965 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
966 /* Don't cache error pages! They cause no end of trouble... */
967 header( 'Cache-control: none' );
968 header( 'Pragma: nocache' );
969 }
970 $msg = $wgSiteNotice;
971 if($msg == '') $msg = wfMsgNoDB( 'noconnect', $error );
972 $text = $msg;
973
974 if($wgUseFileCache) {
975 if($wgTitle) {
976 $t =& $wgTitle;
977 } else {
978 if($title) {
979 $t = Title::newFromURL( $title );
980 } elseif (@/**/$_REQUEST['search']) {
981 $search = $_REQUEST['search'];
982 echo wfMsgNoDB( 'searchdisabled' );
983 echo wfMsgNoDB( 'googlesearch', htmlspecialchars( $search ), $wgInputEncoding );
984 wfErrorExit();
985 } else {
986 $t = Title::newFromText( wfMsgNoDB( 'mainpage' ) );
987 }
988 }
989
990 $cache = new CacheManager( $t );
991 if( $cache->isFileCached() ) {
992 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
993 wfMsgNoDB( 'cachederror' ) . "</b></p>\n";
994
995 $tag = '<div id="article">';
996 $text = str_replace(
997 $tag,
998 $tag . $msg,
999 $cache->fetchPageText() );
1000 }
1001 }
1002
1003 echo $text;
1004 wfErrorExit();
1005 }
1006
1007 ?>