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