Removed most occurences of "wikipedia" replaced by either {{ns:4}} in wikilinks
[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 $table = $this->tableName( $table );
394 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
395
396 if ( $conds !== false ) {
397 if ( is_array( $conds ) ) {
398 $conds = $this->makeList( $conds, LIST_AND );
399 }
400 $sql = "SELECT $vars FROM $table $useIndex WHERE $conds $tailOpts";
401 } else {
402 $sql = "SELECT $vars FROM $table $useIndex $tailOpts";
403 }
404 return $this->query( $sql, $fname );
405 }
406
407 function getArray( $table, $vars, $conds, $fname = "Database::getArray", $options = array() ) {
408 return $this->selectRow( $table, $vars, $conds, $fname, $options );
409 }
410
411 # Single row SELECT wrapper
412 # Aborts or returns FALSE on error
413 #
414 # $vars: the selected variables
415 # $conds: a condition map, terms are ANDed together.
416 # Items with numeric keys are taken to be literal conditions
417 # Takes an array of selected variables, and a condition map, which is ANDed
418 # e.g. selectRow( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
419 # would return an object where $obj->cur_id is the ID of the Astronomy article
420 function selectRow( $table, $vars, $conds, $fname = "Database::selectRow", $options = array() ) {
421 $options['LIMIT'] = 1;
422 $res = $this->select( $table, $vars, $conds, $fname, $options );
423 if ( $res === false || !$this->numRows( $res ) ) {
424 return false;
425 }
426 $obj = $this->fetchObject( $res );
427 $this->freeResult( $res );
428 return $obj;
429
430 }
431
432 # Removes most variables from an SQL query and replaces them with X or N for numbers.
433 # It's only slightly flawed. Don't use for anything important.
434 /* static */ function generalizeSQL( $sql )
435 {
436 # This does the same as the regexp below would do, but in such a way
437 # as to avoid crashing php on some large strings.
438 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
439
440 $sql = str_replace ( "\\\\", "", $sql);
441 $sql = str_replace ( "\\'", "", $sql);
442 $sql = str_replace ( "\\\"", "", $sql);
443 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
444 $sql = preg_replace ('/".*"/s', "'X'", $sql);
445
446 # All newlines, tabs, etc replaced by single space
447 $sql = preg_replace ( "/\s+/", " ", $sql);
448
449 # All numbers => N
450 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
451
452 return $sql;
453 }
454
455 # Determines whether a field exists in a table
456 # Usually aborts on failure
457 # If errors are explicitly ignored, returns NULL on failure
458 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
459 {
460 $table = $this->tableName( $table );
461 $res = $this->query( "DESCRIBE $table", DB_SLAVE, $fname );
462 if ( !$res ) {
463 return NULL;
464 }
465
466 $found = false;
467
468 while ( $row = $this->fetchObject( $res ) ) {
469 if ( $row->Field == $field ) {
470 $found = true;
471 break;
472 }
473 }
474 return $found;
475 }
476
477 # Determines whether an index exists
478 # Usually aborts on failure
479 # If errors are explicitly ignored, returns NULL on failure
480 function indexExists( $table, $index, $fname = "Database::indexExists" )
481 {
482 $info = $this->indexInfo( $table, $index, $fname );
483 if ( is_null( $info ) ) {
484 return NULL;
485 } else {
486 return $info !== false;
487 }
488 }
489
490 function indexInfo( $table, $index, $fname = "Database::indexInfo" ) {
491 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
492 # SHOW INDEX should work for 3.x and up:
493 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
494 $table = $this->tableName( $table );
495 $sql = "SHOW INDEX FROM $table";
496 $res = $this->query( $sql, $fname );
497 if ( !$res ) {
498 return NULL;
499 }
500
501 while ( $row = $this->fetchObject( $res ) ) {
502 if ( $row->Key_name == $index ) {
503 return $row;
504 }
505 }
506 return false;
507 }
508 function tableExists( $table )
509 {
510 $table = $this->tableName( $table );
511 $old = $this->ignoreErrors( true );
512 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
513 $this->ignoreErrors( $old );
514 if( $res ) {
515 $this->freeResult( $res );
516 return true;
517 } else {
518 return false;
519 }
520 }
521
522 function fieldInfo( $table, $field )
523 {
524 $table = $this->tableName( $table );
525 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
526 $n = mysql_num_fields( $res );
527 for( $i = 0; $i < $n; $i++ ) {
528 $meta = mysql_fetch_field( $res, $i );
529 if( $field == $meta->name ) {
530 return $meta;
531 }
532 }
533 return false;
534 }
535
536 function fieldType( $res, $index ) {
537 return mysql_field_type( $res, $index );
538 }
539
540 function indexUnique( $table, $index ) {
541 $indexInfo = $this->indexInfo( $table, $index );
542 if ( !$indexInfo ) {
543 return NULL;
544 }
545 return !$indexInfo->Non_unique;
546 }
547
548 function insertArray( $table, $a, $fname = "Database::insertArray", $options = array() ) {
549 return $this->insert( $table, $a, $fname = "Database::insertArray", $options = array() );
550 }
551
552 # INSERT wrapper, inserts an array into a table
553 #
554 # $a may be a single associative array, or an array of these with numeric keys, for
555 # multi-row insert.
556 #
557 # Usually aborts on failure
558 # If errors are explicitly ignored, returns success
559 function insert( $table, $a, $fname = "Database::insert", $options = array() )
560 {
561 # No rows to insert, easy just return now
562 if ( !count( $a ) ) {
563 return true;
564 }
565
566 $table = $this->tableName( $table );
567 if ( !is_array( $options ) ) {
568 $options = array( $options );
569 }
570 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
571 $multi = true;
572 $keys = array_keys( $a[0] );
573 } else {
574 $multi = false;
575 $keys = array_keys( $a );
576 }
577
578 $sql = 'INSERT ' . implode( ' ', $options ) .
579 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
580
581 if ( $multi ) {
582 $first = true;
583 foreach ( $a as $row ) {
584 if ( $first ) {
585 $first = false;
586 } else {
587 $sql .= ",";
588 }
589 $sql .= '(' . $this->makeList( $row ) . ')';
590 }
591 } else {
592 $sql .= '(' . $this->makeList( $a ) . ')';
593 }
594 return !!$this->query( $sql, $fname );
595 }
596
597 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" ) {
598 return $this->update( $table, $values, $conds, $fname );
599 }
600
601 # UPDATE wrapper, takes a condition array and a SET array
602 function update( $table, $values, $conds, $fname = "Database::update" )
603 {
604 $table = $this->tableName( $table );
605 $sql = "UPDATE $table SET " . $this->makeList( $values, LIST_SET );
606 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
607 $this->query( $sql, $fname );
608 }
609
610 # Makes a wfStrencoded list from an array
611 # $mode: LIST_COMMA - comma separated, no field names
612 # LIST_AND - ANDed WHERE clause (without the WHERE)
613 # LIST_SET - comma separated with field names, like a SET clause
614 function makeList( $a, $mode = LIST_COMMA )
615 {
616 if ( !is_array( $a ) ) {
617 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
618 }
619
620 $first = true;
621 $list = "";
622 foreach ( $a as $field => $value ) {
623 if ( !$first ) {
624 if ( $mode == LIST_AND ) {
625 $list .= " AND ";
626 } else {
627 $list .= ",";
628 }
629 } else {
630 $first = false;
631 }
632 if ( $mode == LIST_AND && is_numeric( $field ) ) {
633 $list .= "($value)";
634 } else {
635 if ( $mode == LIST_AND || $mode == LIST_SET ) {
636 $list .= "$field=";
637 }
638 $list .= $this->addQuotes( $value );
639 }
640 }
641 return $list;
642 }
643
644 function selectDB( $db )
645 {
646 $this->mDBname = $db;
647 mysql_select_db( $db, $this->mConn );
648 }
649
650 function startTimer( $timeout )
651 {
652 global $IP;
653 if( function_exists( "mysql_thread_id" ) ) {
654 # This will kill the query if it's still running after $timeout seconds.
655 $tid = mysql_thread_id( $this->mConn );
656 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
657 }
658 }
659
660 function stopTimer()
661 {
662 }
663
664 function tableName( $name ) {
665 if ( $this->mTablePrefix !== '' ) {
666 if ( strpos( '.', $name ) === false ) {
667 $name = $this->mTablePrefix . $name;
668 }
669 }
670 return $name;
671 }
672
673 function tableNames() {
674 $inArray = func_get_args();
675 $retVal = array();
676 foreach ( $inArray as $name ) {
677 $retVal[$name] = $this->tableName( $name );
678 }
679 return $retVal;
680 }
681
682 function strencode( $s ) {
683 return addslashes( $s );
684 }
685
686 # If it's a string, adds quotes and backslashes
687 # Otherwise returns as-is
688 function addQuotes( $s ) {
689 if ( is_null( $s ) ) {
690 $s = 'NULL';
691 } else if ( !is_numeric( $s ) ) {
692 $s = "'" . $this->strencode( $s ) . "'";
693 }
694 return $s;
695 }
696
697 # Returns an appropriately quoted sequence value for inserting a new row.
698 # MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
699 # subclass will return an integer, and save the value for insertId()
700 function nextSequenceValue( $seqName ) {
701 return NULL;
702 }
703
704 # USE INDEX clause
705 # PostgreSQL doesn't have them and returns ""
706 function useIndexClause( $index ) {
707 return "USE INDEX ($index)";
708 }
709
710 # REPLACE query wrapper
711 # PostgreSQL simulates this with a DELETE followed by INSERT
712 # $row is the row to insert, an associative array
713 # $uniqueIndexes is an array of indexes. Each element may be either a
714 # field name or an array of field names
715 #
716 # It may be more efficient to leave off unique indexes which are unlikely to collide.
717 # However if you do this, you run the risk of encountering errors which wouldn't have
718 # occurred in MySQL
719 function replace( $table, $uniqueIndexes, $rows, $fname = "Database::replace" ) {
720 $table = $this->tableName( $table );
721
722 # Single row case
723 if ( !is_array( reset( $rows ) ) ) {
724 $rows = array( $rows );
725 }
726
727 $sql = "REPLACE INTO $table (" . implode( ',', array_flip( $rows[0] ) ) .") VALUES ";
728 $first = true;
729 foreach ( $rows as $row ) {
730 if ( $first ) {
731 $first = false;
732 } else {
733 $sql .= ",";
734 }
735 $sql .= "(" . $this->makeList( $row ) . ")";
736 }
737 return $this->query( $sql, $fname );
738 }
739
740 # DELETE where the condition is a join
741 # MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
742 #
743 # $delTable is the table to delete from
744 # $joinTable is the other table
745 # $delVar is the variable to join on, in the first table
746 # $joinVar is the variable to join on, in the second table
747 # $conds is a condition array of field names mapped to variables, ANDed together in the WHERE clause
748 #
749 # For safety, an empty $conds will not delete everything. If you want to delete all rows where the
750 # join condition matches, set $conds='*'
751 #
752 # DO NOT put the join condition in $conds
753 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
754 if ( !$conds ) {
755 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
756 }
757
758 $delTable = $this->tableName( $delTable );
759 $joinTable = $this->tableName( $joinTable );
760 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
761 if ( $conds != '*' ) {
762 $sql .= " AND " . $this->makeList( $conds, LIST_AND );
763 }
764
765 return $this->query( $sql, $fname );
766 }
767
768 # Returns the size of a text field, or -1 for "unlimited"
769 function textFieldSize( $table, $field ) {
770 $table = $this->tableName( $table );
771 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
772 $res = $this->query( $sql, "Database::textFieldSize" );
773 $row = $this->fetchObject( $res );
774 $this->freeResult( $res );
775
776 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
777 $size = $m[1];
778 } else {
779 $size = -1;
780 }
781 return $size;
782 }
783
784 function lowPriorityOption() {
785 return 'LOW_PRIORITY';
786 }
787
788 # Use $conds == "*" to delete all rows
789 function delete( $table, $conds, $fname = "Database::delete" ) {
790 if ( !$conds ) {
791 wfDebugDieBacktrace( "Database::delete() called with no conditions" );
792 }
793 $table = $this->tableName( $table );
794 $sql = "DELETE FROM $table ";
795 if ( $conds != '*' ) {
796 $sql .= "WHERE " . $this->makeList( $conds, LIST_AND );
797 }
798 return $this->query( $sql, $fname );
799 }
800
801 # INSERT SELECT wrapper
802 # $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
803 # Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
804 # $conds may be "*" to copy the whole table
805 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
806 $destTable = $this->tableName( $destTable );
807 $srcTable = $this->tableName( $srcTable );
808 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ")" .
809 " SELECT " . implode( ',', $varMap ) .
810 " FROM $srcTable";
811 if ( $conds != '*' ) {
812 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
813 }
814 return $this->query( $sql, $fname );
815 }
816
817 function limitResult($limit,$offset) {
818 return " LIMIT ".(is_numeric($offset)?"{$offset},":"")."{$limit} ";
819 }
820
821 function wasDeadlock() {
822 return $this->lastErrno() == 1213;
823 }
824
825 function deadlockLoop() {
826 $myFname = 'Database::deadlockLoop';
827
828 $this->query( "BEGIN", $myFname );
829 $args = func_get_args();
830 $function = array_shift( $args );
831 $oldIgnore = $dbw->ignoreErrors( true );
832 $tries = DEADLOCK_TRIES;
833 if ( is_array( $function ) ) {
834 $fname = $function[0];
835 } else {
836 $fname = $function;
837 }
838 do {
839 $retVal = call_user_func_array( $function, $args );
840 $error = $this->lastError();
841 $errno = $this->lastErrno();
842 $sql = $this->lastQuery();
843
844 if ( $errno ) {
845 if ( $dbw->wasDeadlock() ) {
846 # Retry
847 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
848 } else {
849 $dbw->reportQueryError( $error, $errno, $sql, $fname );
850 }
851 }
852 } while( $dbw->wasDeadlock && --$tries > 0 );
853 $this->ignoreErrors( $oldIgnore );
854 if ( $tries <= 0 ) {
855 $this->query( "ROLLBACK", $myFname );
856 $this->reportQueryError( $error, $errno, $sql, $fname );
857 return false;
858 } else {
859 $this->query( "COMMIT", $myFname );
860 return $retVal;
861 }
862 }
863
864 # Do a SELECT MASTER_POS_WAIT()
865 function masterPosWait( $file, $pos, $timeout ) {
866 $encFile = $this->strencode( $file );
867 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
868 $res = $this->query( $sql, "Database::masterPosWait" );
869 if ( $res && $row = $this->fetchRow( $res ) ) {
870 $this->freeResult( $res );
871 return $row[0];
872 } else {
873 return false;
874 }
875 }
876
877 # Get the position of the master from SHOW SLAVE STATUS
878 function getSlavePos() {
879 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
880 $row = $this->fetchObject( $res );
881 if ( $row ) {
882 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
883 } else {
884 return array( false, false );
885 }
886 }
887
888 # Get the position of the master from SHOW MASTER STATUS
889 function getMasterPos() {
890 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
891 $row = $this->fetchObject( $res );
892 if ( $row ) {
893 return array( $row->File, $row->Position );
894 } else {
895 return array( false, false );
896 }
897 }
898
899 # Begin a transaction, or if a transaction has already started, continue it
900 function begin( $fname = 'Database::begin' ) {
901 if ( !$this->mTrxLevel ) {
902 $this->immediateBegin( $fname );
903 } else {
904 $this->mTrxLevel++;
905 }
906 }
907
908 # End a transaction, or decrement the nest level if transactions are nested
909 function commit( $fname = 'Database::commit' ) {
910 if ( $this->mTrxLevel ) {
911 $this->mTrxLevel--;
912 }
913 if ( !$this->mTrxLevel ) {
914 $this->immediateCommit( $fname );
915 }
916 }
917
918 # Rollback a transaction
919 function rollback( $fname = 'Database::rollback' ) {
920 $this->query( 'ROLLBACK', $fname );
921 $this->mTrxLevel = 0;
922 }
923
924 # Begin a transaction, committing any previously open transaction
925 function immediateBegin( $fname = 'Database::immediateBegin' ) {
926 $this->query( 'BEGIN', $fname );
927 $this->mTrxLevel = 1;
928 }
929
930 # Commit transaction, if one is open
931 function immediateCommit( $fname = 'Database::immediateCommit' ) {
932 $this->query( 'COMMIT', $fname );
933 $this->mTrxLevel = 0;
934 }
935
936 # Return MW-style timestamp used for MySQL schema
937 function timestamp( $ts=0 ) {
938 return wfTimestamp(TS_MW,$ts);
939 }
940 }
941
942 class DatabaseMysql extends Database {
943 # Inherit all
944 }
945
946 #------------------------------------------------------------------------------
947 # Global functions
948 #------------------------------------------------------------------------------
949
950 /* Standard fail function, called by default when a connection cannot be established
951 Displays the file cache if possible */
952 function wfEmergencyAbort( &$conn, $error ) {
953 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
954
955 if( !headers_sent() ) {
956 header( "HTTP/1.0 500 Internal Server Error" );
957 header( "Content-type: text/html; charset=$wgOutputEncoding" );
958 /* Don't cache error pages! They cause no end of trouble... */
959 header( "Cache-control: none" );
960 header( "Pragma: nocache" );
961 }
962 $msg = $wgSiteNotice;
963 if($msg == "") $msg = wfMsgNoDB( "noconnect", $error );
964 $text = $msg;
965
966 if($wgUseFileCache) {
967 if($wgTitle) {
968 $t =& $wgTitle;
969 } else {
970 if($title) {
971 $t = Title::newFromURL( $title );
972 } elseif (@/**/$_REQUEST['search']) {
973 $search = $_REQUEST['search'];
974 echo wfMsgNoDB( "searchdisabled" );
975 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
976 wfErrorExit();
977 } else {
978 $t = Title::newFromText( wfMsgNoDB( "mainpage" ) );
979 }
980 }
981
982 $cache = new CacheManager( $t );
983 if( $cache->isFileCached() ) {
984 $msg = "<p style='color: red'><b>$msg<br />\n" .
985 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
986
987 $tag = "<div id='article'>";
988 $text = str_replace(
989 $tag,
990 $tag . $msg,
991 $cache->fetchPageText() );
992 }
993 }
994
995 echo $text;
996 wfErrorExit();
997 }
998
999 function wfLimitResult( $limit, $offset ) {
1000 return " LIMIT ".(is_numeric($offset)?"{$offset},":"")."{$limit} ";
1001 }
1002
1003 ?>