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