In Database::getLag(): Add some more I/O thread states.
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * @file
6 * @ingroup Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
9 */
10
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
17
18 /**
19 * Database abstraction object
20 * @ingroup Database
21 */
22 abstract class DatabaseBase {
23
24 #------------------------------------------------------------------------------
25 # Variables
26 #------------------------------------------------------------------------------
27
28 protected $mLastQuery = '';
29 protected $mDoneWrites = false;
30 protected $mPHPError = false;
31
32 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
33 protected $mOpened = false;
34
35 protected $mFailFunction;
36 protected $mTablePrefix;
37 protected $mFlags;
38 protected $mTrxLevel = 0;
39 protected $mErrorCount = 0;
40 protected $mLBInfo = array();
41 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 protected $mDefaultBigSelects = null;
43
44 #------------------------------------------------------------------------------
45 # Accessors
46 #------------------------------------------------------------------------------
47 # These optionally set a variable and return the previous state
48
49 /**
50 * Fail function, takes a Database as a parameter
51 * Set to false for default, 1 for ignore errors
52 */
53 function failFunction( $function = NULL ) {
54 return wfSetVar( $this->mFailFunction, $function );
55 }
56
57 /**
58 * Output page, used for reporting errors
59 * FALSE means discard output
60 */
61 function setOutputPage( $out ) {
62 wfDeprecated( __METHOD__ );
63 }
64
65 /**
66 * Boolean, controls output of large amounts of debug information
67 */
68 function debug( $debug = NULL ) {
69 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
70 }
71
72 /**
73 * Turns buffering of SQL result sets on (true) or off (false).
74 * Default is "on" and it should not be changed without good reasons.
75 */
76 function bufferResults( $buffer = NULL ) {
77 if ( is_null( $buffer ) ) {
78 return !(bool)( $this->mFlags & DBO_NOBUFFER );
79 } else {
80 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
81 }
82 }
83
84 /**
85 * Turns on (false) or off (true) the automatic generation and sending
86 * of a "we're sorry, but there has been a database error" page on
87 * database errors. Default is on (false). When turned off, the
88 * code should use lastErrno() and lastError() to handle the
89 * situation as appropriate.
90 */
91 function ignoreErrors( $ignoreErrors = NULL ) {
92 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
93 }
94
95 /**
96 * The current depth of nested transactions
97 * @param $level Integer: , default NULL.
98 */
99 function trxLevel( $level = NULL ) {
100 return wfSetVar( $this->mTrxLevel, $level );
101 }
102
103 /**
104 * Number of errors logged, only useful when errors are ignored
105 */
106 function errorCount( $count = NULL ) {
107 return wfSetVar( $this->mErrorCount, $count );
108 }
109
110 function tablePrefix( $prefix = null ) {
111 return wfSetVar( $this->mTablePrefix, $prefix );
112 }
113
114 /**
115 * Properties passed down from the server info array of the load balancer
116 */
117 function getLBInfo( $name = NULL ) {
118 if ( is_null( $name ) ) {
119 return $this->mLBInfo;
120 } else {
121 if ( array_key_exists( $name, $this->mLBInfo ) ) {
122 return $this->mLBInfo[$name];
123 } else {
124 return NULL;
125 }
126 }
127 }
128
129 function setLBInfo( $name, $value = NULL ) {
130 if ( is_null( $value ) ) {
131 $this->mLBInfo = $name;
132 } else {
133 $this->mLBInfo[$name] = $value;
134 }
135 }
136
137 /**
138 * Set lag time in seconds for a fake slave
139 */
140 function setFakeSlaveLag( $lag ) {
141 $this->mFakeSlaveLag = $lag;
142 }
143
144 /**
145 * Make this connection a fake master
146 */
147 function setFakeMaster( $enabled = true ) {
148 $this->mFakeMaster = $enabled;
149 }
150
151 /**
152 * Returns true if this database supports (and uses) cascading deletes
153 */
154 function cascadingDeletes() {
155 return false;
156 }
157
158 /**
159 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
160 */
161 function cleanupTriggers() {
162 return false;
163 }
164
165 /**
166 * Returns true if this database is strict about what can be put into an IP field.
167 * Specifically, it uses a NULL value instead of an empty string.
168 */
169 function strictIPs() {
170 return false;
171 }
172
173 /**
174 * Returns true if this database uses timestamps rather than integers
175 */
176 function realTimestamps() {
177 return false;
178 }
179
180 /**
181 * Returns true if this database does an implicit sort when doing GROUP BY
182 */
183 function implicitGroupby() {
184 return true;
185 }
186
187 /**
188 * Returns true if this database does an implicit order by when the column has an index
189 * For example: SELECT page_title FROM page LIMIT 1
190 */
191 function implicitOrderby() {
192 return true;
193 }
194
195 /**
196 * Returns true if this database requires that SELECT DISTINCT queries require that all
197 ORDER BY expressions occur in the SELECT list per the SQL92 standard
198 */
199 function standardSelectDistinct() {
200 return true;
201 }
202
203 /**
204 * Returns true if this database can do a native search on IP columns
205 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
206 */
207 function searchableIPs() {
208 return false;
209 }
210
211 /**
212 * Returns true if this database can use functional indexes
213 */
214 function functionalIndexes() {
215 return false;
216 }
217
218 /**
219 * Return the last query that went through Database::query()
220 * @return String
221 */
222 function lastQuery() { return $this->mLastQuery; }
223
224
225 /**
226 * Returns true if the connection may have been used for write queries.
227 * Should return true if unsure.
228 */
229 function doneWrites() { return $this->mDoneWrites; }
230
231 /**
232 * Is a connection to the database open?
233 * @return Boolean
234 */
235 function isOpen() { return $this->mOpened; }
236
237 function setFlag( $flag ) {
238 $this->mFlags |= $flag;
239 }
240
241 function clearFlag( $flag ) {
242 $this->mFlags &= ~$flag;
243 }
244
245 function getFlag( $flag ) {
246 return !!($this->mFlags & $flag);
247 }
248
249 /**
250 * General read-only accessor
251 */
252 function getProperty( $name ) {
253 return $this->$name;
254 }
255
256 function getWikiID() {
257 if( $this->mTablePrefix ) {
258 return "{$this->mDBname}-{$this->mTablePrefix}";
259 } else {
260 return $this->mDBname;
261 }
262 }
263
264 #------------------------------------------------------------------------------
265 # Other functions
266 #------------------------------------------------------------------------------
267
268 /**
269 * Constructor.
270 * @param $server String: database server host
271 * @param $user String: database user name
272 * @param $password String: database user password
273 * @param $dbName String: database name
274 * @param $failFunction
275 * @param $flags
276 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
277 */
278 function __construct( $server = false, $user = false, $password = false, $dbName = false,
279 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
280
281 global $wgOut, $wgDBprefix, $wgCommandLineMode;
282 # Can't get a reference if it hasn't been set yet
283 if ( !isset( $wgOut ) ) {
284 $wgOut = NULL;
285 }
286
287 $this->mFailFunction = $failFunction;
288 $this->mFlags = $flags;
289
290 if ( $this->mFlags & DBO_DEFAULT ) {
291 if ( $wgCommandLineMode ) {
292 $this->mFlags &= ~DBO_TRX;
293 } else {
294 $this->mFlags |= DBO_TRX;
295 }
296 }
297
298 /*
299 // Faster read-only access
300 if ( wfReadOnly() ) {
301 $this->mFlags |= DBO_PERSISTENT;
302 $this->mFlags &= ~DBO_TRX;
303 }*/
304
305 /** Get the default table prefix*/
306 if ( $tablePrefix == 'get from global' ) {
307 $this->mTablePrefix = $wgDBprefix;
308 } else {
309 $this->mTablePrefix = $tablePrefix;
310 }
311
312 if ( $server ) {
313 $this->open( $server, $user, $password, $dbName );
314 }
315 }
316
317 /**
318 * Same as new DatabaseMysql( ... ), kept for backward compatibility
319 * @param $server String: database server host
320 * @param $user String: database user name
321 * @param $password String: database user password
322 * @param $dbName String: database name
323 * @param failFunction
324 * @param $flags
325 */
326 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
327 {
328 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
329 }
330
331 /**
332 * Usually aborts on failure
333 * If the failFunction is set to a non-zero integer, returns success
334 * @param $server String: database server host
335 * @param $user String: database user name
336 * @param $password String: database user password
337 * @param $dbName String: database name
338 */
339 abstract function open( $server, $user, $password, $dbName );
340
341 protected function installErrorHandler() {
342 $this->mPHPError = false;
343 $this->htmlErrors = ini_set( 'html_errors', '0' );
344 set_error_handler( array( $this, 'connectionErrorHandler' ) );
345 }
346
347 protected function restoreErrorHandler() {
348 restore_error_handler();
349 if ( $this->htmlErrors !== false ) {
350 ini_set( 'html_errors', $this->htmlErrors );
351 }
352 if ( $this->mPHPError ) {
353 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
354 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
355 return $error;
356 } else {
357 return false;
358 }
359 }
360
361 protected function connectionErrorHandler( $errno, $errstr ) {
362 $this->mPHPError = $errstr;
363 }
364
365 /**
366 * Closes a database connection.
367 * if it is open : commits any open transactions
368 *
369 * @return Bool operation success. true if already closed.
370 */
371 function close() {
372 # Stub, should probably be overridden
373 return true;
374 }
375
376 /**
377 * @param $error String: fallback error message, used if none is given by MySQL
378 */
379 function reportConnectionError( $error = 'Unknown error' ) {
380 $myError = $this->lastError();
381 if ( $myError ) {
382 $error = $myError;
383 }
384
385 if ( $this->mFailFunction ) {
386 # Legacy error handling method
387 if ( !is_int( $this->mFailFunction ) ) {
388 $ff = $this->mFailFunction;
389 $ff( $this, $error );
390 }
391 } else {
392 # New method
393 throw new DBConnectionError( $this, $error );
394 }
395 }
396
397 /**
398 * Determine whether a query writes to the DB.
399 * Should return true if unsure.
400 */
401 function isWriteQuery( $sql ) {
402 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW)\b/i', $sql );
403 }
404
405 /**
406 * Usually aborts on failure. If errors are explicitly ignored, returns success.
407 *
408 * @param $sql String: SQL query
409 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
410 * comment (you can use __METHOD__ or add some extra info)
411 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
412 * maybe best to catch the exception instead?
413 * @return true for a successful write query, ResultWrapper object for a successful read query,
414 * or false on failure if $tempIgnore set
415 * @throws DBQueryError Thrown when the database returns an error of any kind
416 */
417 public function query( $sql, $fname = '', $tempIgnore = false ) {
418 global $wgProfiler;
419
420 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
421 if ( isset( $wgProfiler ) ) {
422 # generalizeSQL will probably cut down the query to reasonable
423 # logging size most of the time. The substr is really just a sanity check.
424
425 # Who's been wasting my precious column space? -- TS
426 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
427
428 if ( $isMaster ) {
429 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
430 $totalProf = 'Database::query-master';
431 } else {
432 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
433 $totalProf = 'Database::query';
434 }
435 wfProfileIn( $totalProf );
436 wfProfileIn( $queryProf );
437 }
438
439 $this->mLastQuery = $sql;
440 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
441 // Set a flag indicating that writes have been done
442 wfDebug( __METHOD__.": Writes done: $sql\n" );
443 $this->mDoneWrites = true;
444 }
445
446 # Add a comment for easy SHOW PROCESSLIST interpretation
447 #if ( $fname ) {
448 global $wgUser;
449 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
450 $userName = $wgUser->getName();
451 if ( mb_strlen( $userName ) > 15 ) {
452 $userName = mb_substr( $userName, 0, 15 ) . '...';
453 }
454 $userName = str_replace( '/', '', $userName );
455 } else {
456 $userName = '';
457 }
458 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
459 #} else {
460 # $commentedSql = $sql;
461 #}
462
463 # If DBO_TRX is set, start a transaction
464 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
465 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
466 // avoid establishing transactions for SHOW and SET statements too -
467 // that would delay transaction initializations to once connection
468 // is really used by application
469 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
470 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
471 $this->begin();
472 }
473
474 if ( $this->debug() ) {
475 $sqlx = substr( $commentedSql, 0, 500 );
476 $sqlx = strtr( $sqlx, "\t\n", ' ' );
477 if ( $isMaster ) {
478 wfDebug( "SQL-master: $sqlx\n" );
479 } else {
480 wfDebug( "SQL: $sqlx\n" );
481 }
482 }
483
484 if ( istainted( $sql ) & TC_MYSQL ) {
485 throw new MWException( 'Tainted query found' );
486 }
487
488 # Do the query and handle errors
489 $ret = $this->doQuery( $commentedSql );
490
491 # Try reconnecting if the connection was lost
492 if ( false === $ret && $this->wasErrorReissuable() ) {
493 # Transaction is gone, like it or not
494 $this->mTrxLevel = 0;
495 wfDebug( "Connection lost, reconnecting...\n" );
496 if ( $this->ping() ) {
497 wfDebug( "Reconnected\n" );
498 $sqlx = substr( $commentedSql, 0, 500 );
499 $sqlx = strtr( $sqlx, "\t\n", ' ' );
500 global $wgRequestTime;
501 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
502 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
503 $ret = $this->doQuery( $commentedSql );
504 } else {
505 wfDebug( "Failed\n" );
506 }
507 }
508
509 if ( false === $ret ) {
510 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
511 }
512
513 if ( isset( $wgProfiler ) ) {
514 wfProfileOut( $queryProf );
515 wfProfileOut( $totalProf );
516 }
517 return $this->resultObject( $ret );
518 }
519
520 /**
521 * The DBMS-dependent part of query()
522 * @param $sql String: SQL query.
523 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
524 * @private
525 */
526 /*private*/ abstract function doQuery( $sql );
527
528 /**
529 * @param $error String
530 * @param $errno Integer
531 * @param $sql String
532 * @param $fname String
533 * @param $tempIgnore Boolean
534 */
535 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
536 global $wgCommandLineMode;
537 # Ignore errors during error handling to avoid infinite recursion
538 $ignore = $this->ignoreErrors( true );
539 ++$this->mErrorCount;
540
541 if( $ignore || $tempIgnore ) {
542 wfDebug("SQL ERROR (ignored): $error\n");
543 $this->ignoreErrors( $ignore );
544 } else {
545 $sql1line = str_replace( "\n", "\\n", $sql );
546 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
547 wfDebug("SQL ERROR: " . $error . "\n");
548 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
549 }
550 }
551
552
553 /**
554 * Intended to be compatible with the PEAR::DB wrapper functions.
555 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
556 *
557 * ? = scalar value, quoted as necessary
558 * ! = raw SQL bit (a function for instance)
559 * & = filename; reads the file and inserts as a blob
560 * (we don't use this though...)
561 */
562 function prepare( $sql, $func = 'Database::prepare' ) {
563 /* MySQL doesn't support prepared statements (yet), so just
564 pack up the query for reference. We'll manually replace
565 the bits later. */
566 return array( 'query' => $sql, 'func' => $func );
567 }
568
569 function freePrepared( $prepared ) {
570 /* No-op for MySQL */
571 }
572
573 /**
574 * Execute a prepared query with the various arguments
575 * @param $prepared String: the prepared sql
576 * @param $args Mixed: Either an array here, or put scalars as varargs
577 */
578 function execute( $prepared, $args = null ) {
579 if( !is_array( $args ) ) {
580 # Pull the var args
581 $args = func_get_args();
582 array_shift( $args );
583 }
584 $sql = $this->fillPrepared( $prepared['query'], $args );
585 return $this->query( $sql, $prepared['func'] );
586 }
587
588 /**
589 * Prepare & execute an SQL statement, quoting and inserting arguments
590 * in the appropriate places.
591 * @param $query String
592 * @param $args ...
593 */
594 function safeQuery( $query, $args = null ) {
595 $prepared = $this->prepare( $query, 'Database::safeQuery' );
596 if( !is_array( $args ) ) {
597 # Pull the var args
598 $args = func_get_args();
599 array_shift( $args );
600 }
601 $retval = $this->execute( $prepared, $args );
602 $this->freePrepared( $prepared );
603 return $retval;
604 }
605
606 /**
607 * For faking prepared SQL statements on DBs that don't support
608 * it directly.
609 * @param $preparedQuery String: a 'preparable' SQL statement
610 * @param $args Array of arguments to fill it with
611 * @return string executable SQL
612 */
613 function fillPrepared( $preparedQuery, $args ) {
614 reset( $args );
615 $this->preparedArgs =& $args;
616 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
617 array( &$this, 'fillPreparedArg' ), $preparedQuery );
618 }
619
620 /**
621 * preg_callback func for fillPrepared()
622 * The arguments should be in $this->preparedArgs and must not be touched
623 * while we're doing this.
624 *
625 * @param $matches Array
626 * @return String
627 * @private
628 */
629 function fillPreparedArg( $matches ) {
630 switch( $matches[1] ) {
631 case '\\?': return '?';
632 case '\\!': return '!';
633 case '\\&': return '&';
634 }
635 list( /* $n */ , $arg ) = each( $this->preparedArgs );
636 switch( $matches[1] ) {
637 case '?': return $this->addQuotes( $arg );
638 case '!': return $arg;
639 case '&':
640 # return $this->addQuotes( file_get_contents( $arg ) );
641 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
642 default:
643 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
644 }
645 }
646
647 /**
648 * Free a result object
649 * @param $res Mixed: A SQL result
650 */
651 function freeResult( $res ) {
652 # Stub. Might not really need to be overridden, since results should
653 # be freed by PHP when the variable goes out of scope anyway.
654 }
655
656 /**
657 * Fetch the next row from the given result object, in object form.
658 * Fields can be retrieved with $row->fieldname, with fields acting like
659 * member variables.
660 *
661 * @param $res SQL result object as returned from Database::query(), etc.
662 * @return MySQL row object
663 * @throws DBUnexpectedError Thrown if the database returns an error
664 */
665 abstract function fetchObject( $res );
666
667 /**
668 * Fetch the next row from the given result object, in associative array
669 * form. Fields are retrieved with $row['fieldname'].
670 *
671 * @param $res SQL result object as returned from Database::query(), etc.
672 * @return MySQL row object
673 * @throws DBUnexpectedError Thrown if the database returns an error
674 */
675 abstract function fetchRow( $res );
676
677 /**
678 * Get the number of rows in a result object
679 * @param $res Mixed: A SQL result
680 */
681 abstract function numRows( $res );
682
683 /**
684 * Get the number of fields in a result object
685 * See documentation for mysql_num_fields()
686 * @param $res Mixed: A SQL result
687 */
688 abstract function numFields( $res );
689
690 /**
691 * Get a field name in a result object
692 * See documentation for mysql_field_name():
693 * http://www.php.net/mysql_field_name
694 * @param $res Mixed: A SQL result
695 * @param $n Integer
696 */
697 abstract function fieldName( $res, $n );
698
699 /**
700 * Get the inserted value of an auto-increment row
701 *
702 * The value inserted should be fetched from nextSequenceValue()
703 *
704 * Example:
705 * $id = $dbw->nextSequenceValue('page_page_id_seq');
706 * $dbw->insert('page',array('page_id' => $id));
707 * $id = $dbw->insertId();
708 */
709 abstract function insertId();
710
711 /**
712 * Change the position of the cursor in a result object
713 * See mysql_data_seek()
714 * @param $res Mixed: A SQL result
715 * @param $row Mixed: Either MySQL row or ResultWrapper
716 */
717 abstract function dataSeek( $res, $row );
718
719 /**
720 * Get the last error number
721 * See mysql_errno()
722 */
723 abstract function lastErrno();
724
725 /**
726 * Get a description of the last error
727 * See mysql_error() for more details
728 */
729 abstract function lastError();
730
731 /**
732 * Get the number of rows affected by the last write query
733 * See mysql_affected_rows() for more details
734 */
735 abstract function affectedRows();
736
737 /**
738 * Simple UPDATE wrapper
739 * Usually aborts on failure
740 * If errors are explicitly ignored, returns success
741 *
742 * This function exists for historical reasons, Database::update() has a more standard
743 * calling convention and feature set
744 */
745 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
746 $table = $this->tableName( $table );
747 $sql = "UPDATE $table SET $var = '" .
748 $this->strencode( $value ) . "' WHERE ($cond)";
749 return (bool)$this->query( $sql, $fname );
750 }
751
752 /**
753 * Simple SELECT wrapper, returns a single field, input must be encoded
754 * Usually aborts on failure
755 * If errors are explicitly ignored, returns FALSE on failure
756 */
757 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
758 if ( !is_array( $options ) ) {
759 $options = array( $options );
760 }
761 $options['LIMIT'] = 1;
762
763 $res = $this->select( $table, $var, $cond, $fname, $options );
764 if ( $res === false || !$this->numRows( $res ) ) {
765 return false;
766 }
767 $row = $this->fetchRow( $res );
768 if ( $row !== false ) {
769 $this->freeResult( $res );
770 return reset( $row );
771 } else {
772 return false;
773 }
774 }
775
776 /**
777 * Returns an optional USE INDEX clause to go after the table, and a
778 * string to go at the end of the query
779 *
780 * @private
781 *
782 * @param $options Array: associative array of options to be turned into
783 * an SQL query, valid keys are listed in the function.
784 * @return Array
785 */
786 function makeSelectOptions( $options ) {
787 $preLimitTail = $postLimitTail = '';
788 $startOpts = '';
789
790 $noKeyOptions = array();
791 foreach ( $options as $key => $option ) {
792 if ( is_numeric( $key ) ) {
793 $noKeyOptions[$option] = true;
794 }
795 }
796
797 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
798 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
799 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
800
801 //if (isset($options['LIMIT'])) {
802 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
803 // isset($options['OFFSET']) ? $options['OFFSET']
804 // : false);
805 //}
806
807 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
808 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
809 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
810
811 # Various MySQL extensions
812 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
813 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
814 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
815 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
816 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
817 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
818 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
819 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
820
821 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
822 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
823 } else {
824 $useIndex = '';
825 }
826
827 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
828 }
829
830 /**
831 * SELECT wrapper
832 *
833 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
834 * @param $vars Mixed: Array or string, field name(s) to be retrieved
835 * @param $conds Mixed: Array or string, condition(s) for WHERE
836 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
837 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
838 * see Database::makeSelectOptions code for list of supported stuff
839 * @param $join_conds Array: Associative array of table join conditions (optional)
840 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
841 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
842 */
843 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
844 {
845 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
846 return $this->query( $sql, $fname );
847 }
848
849 /**
850 * SELECT wrapper
851 *
852 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
853 * @param $vars Mixed: Array or string, field name(s) to be retrieved
854 * @param $conds Mixed: Array or string, condition(s) for WHERE
855 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
856 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
857 * see Database::makeSelectOptions code for list of supported stuff
858 * @param $join_conds Array: Associative array of table join conditions (optional)
859 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
860 * @return string, the SQL text
861 */
862 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
863 if( is_array( $vars ) ) {
864 $vars = implode( ',', $vars );
865 }
866 if( !is_array( $options ) ) {
867 $options = array( $options );
868 }
869 if( is_array( $table ) ) {
870 if ( !empty($join_conds) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
871 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
872 else
873 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
874 } elseif ($table!='') {
875 if ($table{0}==' ') {
876 $from = ' FROM ' . $table;
877 } else {
878 $from = ' FROM ' . $this->tableName( $table );
879 }
880 } else {
881 $from = '';
882 }
883
884 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
885
886 if( !empty( $conds ) ) {
887 if ( is_array( $conds ) ) {
888 $conds = $this->makeList( $conds, LIST_AND );
889 }
890 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
891 } else {
892 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
893 }
894
895 if (isset($options['LIMIT']))
896 $sql = $this->limitResult($sql, $options['LIMIT'],
897 isset($options['OFFSET']) ? $options['OFFSET'] : false);
898 $sql = "$sql $postLimitTail";
899
900 if (isset($options['EXPLAIN'])) {
901 $sql = 'EXPLAIN ' . $sql;
902 }
903 return $sql;
904 }
905
906 /**
907 * Single row SELECT wrapper
908 * Aborts or returns FALSE on error
909 *
910 * @param $table String: table name
911 * @param $vars String: the selected variables
912 * @param $conds Array: a condition map, terms are ANDed together.
913 * Items with numeric keys are taken to be literal conditions
914 * Takes an array of selected variables, and a condition map, which is ANDed
915 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
916 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
917 * $obj- >page_id is the ID of the Astronomy article
918 * @param $fname String: Calling function name
919 * @param $options Array
920 * @param $join_conds Array
921 *
922 * @todo migrate documentation to phpdocumentor format
923 */
924 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
925 $options['LIMIT'] = 1;
926 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
927 if ( $res === false )
928 return false;
929 if ( !$this->numRows($res) ) {
930 $this->freeResult($res);
931 return false;
932 }
933 $obj = $this->fetchObject( $res );
934 $this->freeResult( $res );
935 return $obj;
936
937 }
938
939 /**
940 * Estimate rows in dataset
941 * Returns estimated count, based on EXPLAIN output
942 * Takes same arguments as Database::select()
943 */
944
945 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
946 $options['EXPLAIN']=true;
947 $res = $this->select ($table, $vars, $conds, $fname, $options );
948 if ( $res === false )
949 return false;
950 if (!$this->numRows($res)) {
951 $this->freeResult($res);
952 return 0;
953 }
954
955 $rows=1;
956
957 while( $plan = $this->fetchObject( $res ) ) {
958 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
959 }
960
961 $this->freeResult($res);
962 return $rows;
963 }
964
965
966 /**
967 * Removes most variables from an SQL query and replaces them with X or N for numbers.
968 * It's only slightly flawed. Don't use for anything important.
969 *
970 * @param $sql String: A SQL Query
971 */
972 static function generalizeSQL( $sql ) {
973 # This does the same as the regexp below would do, but in such a way
974 # as to avoid crashing php on some large strings.
975 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
976
977 $sql = str_replace ( "\\\\", '', $sql);
978 $sql = str_replace ( "\\'", '', $sql);
979 $sql = str_replace ( "\\\"", '', $sql);
980 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
981 $sql = preg_replace ('/".*"/s', "'X'", $sql);
982
983 # All newlines, tabs, etc replaced by single space
984 $sql = preg_replace ( '/\s+/', ' ', $sql);
985
986 # All numbers => N
987 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
988
989 return $sql;
990 }
991
992 /**
993 * Determines whether a field exists in a table
994 * Usually aborts on failure
995 * If errors are explicitly ignored, returns NULL on failure
996 */
997 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
998 $table = $this->tableName( $table );
999 $res = $this->query( 'DESCRIBE '.$table, $fname );
1000 if ( !$res ) {
1001 return NULL;
1002 }
1003
1004 $found = false;
1005
1006 while ( $row = $this->fetchObject( $res ) ) {
1007 if ( $row->Field == $field ) {
1008 $found = true;
1009 break;
1010 }
1011 }
1012 return $found;
1013 }
1014
1015 /**
1016 * Determines whether an index exists
1017 * Usually aborts on failure
1018 * If errors are explicitly ignored, returns NULL on failure
1019 */
1020 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1021 $info = $this->indexInfo( $table, $index, $fname );
1022 if ( is_null( $info ) ) {
1023 return NULL;
1024 } else {
1025 return $info !== false;
1026 }
1027 }
1028
1029
1030 /**
1031 * Get information about an index into an object
1032 * Returns false if the index does not exist
1033 */
1034 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1035 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1036 # SHOW INDEX should work for 3.x and up:
1037 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1038 $table = $this->tableName( $table );
1039 $index = $this->indexName( $index );
1040 $sql = 'SHOW INDEX FROM '.$table;
1041 $res = $this->query( $sql, $fname );
1042 if ( !$res ) {
1043 return NULL;
1044 }
1045
1046 $result = array();
1047 while ( $row = $this->fetchObject( $res ) ) {
1048 if ( $row->Key_name == $index ) {
1049 $result[] = $row;
1050 }
1051 }
1052 $this->freeResult($res);
1053
1054 return empty($result) ? false : $result;
1055 }
1056
1057 /**
1058 * Query whether a given table exists
1059 */
1060 function tableExists( $table ) {
1061 $table = $this->tableName( $table );
1062 $old = $this->ignoreErrors( true );
1063 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1064 $this->ignoreErrors( $old );
1065 if( $res ) {
1066 $this->freeResult( $res );
1067 return true;
1068 } else {
1069 return false;
1070 }
1071 }
1072
1073 /**
1074 * mysql_fetch_field() wrapper
1075 * Returns false if the field doesn't exist
1076 *
1077 * @param $table
1078 * @param $field
1079 */
1080 abstract function fieldInfo( $table, $field );
1081
1082 /**
1083 * mysql_field_type() wrapper
1084 */
1085 function fieldType( $res, $index ) {
1086 if ( $res instanceof ResultWrapper ) {
1087 $res = $res->result;
1088 }
1089 return mysql_field_type( $res, $index );
1090 }
1091
1092 /**
1093 * Determines if a given index is unique
1094 */
1095 function indexUnique( $table, $index ) {
1096 $indexInfo = $this->indexInfo( $table, $index );
1097 if ( !$indexInfo ) {
1098 return NULL;
1099 }
1100 return !$indexInfo[0]->Non_unique;
1101 }
1102
1103 /**
1104 * INSERT wrapper, inserts an array into a table
1105 *
1106 * $a may be a single associative array, or an array of these with numeric keys, for
1107 * multi-row insert.
1108 *
1109 * Usually aborts on failure
1110 * If errors are explicitly ignored, returns success
1111 */
1112 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1113 # No rows to insert, easy just return now
1114 if ( !count( $a ) ) {
1115 return true;
1116 }
1117
1118 $table = $this->tableName( $table );
1119 if ( !is_array( $options ) ) {
1120 $options = array( $options );
1121 }
1122 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1123 $multi = true;
1124 $keys = array_keys( $a[0] );
1125 } else {
1126 $multi = false;
1127 $keys = array_keys( $a );
1128 }
1129
1130 $sql = 'INSERT ' . implode( ' ', $options ) .
1131 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1132
1133 if ( $multi ) {
1134 $first = true;
1135 foreach ( $a as $row ) {
1136 if ( $first ) {
1137 $first = false;
1138 } else {
1139 $sql .= ',';
1140 }
1141 $sql .= '(' . $this->makeList( $row ) . ')';
1142 }
1143 } else {
1144 $sql .= '(' . $this->makeList( $a ) . ')';
1145 }
1146 return (bool)$this->query( $sql, $fname );
1147 }
1148
1149 /**
1150 * Make UPDATE options for the Database::update function
1151 *
1152 * @private
1153 * @param $options Array: The options passed to Database::update
1154 * @return string
1155 */
1156 function makeUpdateOptions( $options ) {
1157 if( !is_array( $options ) ) {
1158 $options = array( $options );
1159 }
1160 $opts = array();
1161 if ( in_array( 'LOW_PRIORITY', $options ) )
1162 $opts[] = $this->lowPriorityOption();
1163 if ( in_array( 'IGNORE', $options ) )
1164 $opts[] = 'IGNORE';
1165 return implode(' ', $opts);
1166 }
1167
1168 /**
1169 * UPDATE wrapper, takes a condition array and a SET array
1170 *
1171 * @param $table String: The table to UPDATE
1172 * @param $values Array: An array of values to SET
1173 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1174 * @param $fname String: The Class::Function calling this function
1175 * (for the log)
1176 * @param $options Array: An array of UPDATE options, can be one or
1177 * more of IGNORE, LOW_PRIORITY
1178 * @return Boolean
1179 */
1180 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1181 $table = $this->tableName( $table );
1182 $opts = $this->makeUpdateOptions( $options );
1183 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1184 if ( $conds != '*' ) {
1185 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1186 }
1187 return $this->query( $sql, $fname );
1188 }
1189
1190 /**
1191 * Makes an encoded list of strings from an array
1192 * $mode:
1193 * LIST_COMMA - comma separated, no field names
1194 * LIST_AND - ANDed WHERE clause (without the WHERE)
1195 * LIST_OR - ORed WHERE clause (without the WHERE)
1196 * LIST_SET - comma separated with field names, like a SET clause
1197 * LIST_NAMES - comma separated field names
1198 */
1199 function makeList( $a, $mode = LIST_COMMA ) {
1200 if ( !is_array( $a ) ) {
1201 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1202 }
1203
1204 $first = true;
1205 $list = '';
1206 foreach ( $a as $field => $value ) {
1207 if ( !$first ) {
1208 if ( $mode == LIST_AND ) {
1209 $list .= ' AND ';
1210 } elseif($mode == LIST_OR) {
1211 $list .= ' OR ';
1212 } else {
1213 $list .= ',';
1214 }
1215 } else {
1216 $first = false;
1217 }
1218 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1219 $list .= "($value)";
1220 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1221 $list .= "$value";
1222 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1223 if( count( $value ) == 0 ) {
1224 throw new MWException( __METHOD__.': empty input' );
1225 } elseif( count( $value ) == 1 ) {
1226 // Special-case single values, as IN isn't terribly efficient
1227 // Don't necessarily assume the single key is 0; we don't
1228 // enforce linear numeric ordering on other arrays here.
1229 $value = array_values( $value );
1230 $list .= $field." = ".$this->addQuotes( $value[0] );
1231 } else {
1232 $list .= $field." IN (".$this->makeList($value).") ";
1233 }
1234 } elseif( $value === null ) {
1235 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1236 $list .= "$field IS ";
1237 } elseif ( $mode == LIST_SET ) {
1238 $list .= "$field = ";
1239 }
1240 $list .= 'NULL';
1241 } else {
1242 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1243 $list .= "$field = ";
1244 }
1245 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1246 }
1247 }
1248 return $list;
1249 }
1250
1251 /**
1252 * Bitwise operations
1253 */
1254
1255 function bitNot($field) {
1256 return "(~$bitField)";
1257 }
1258
1259 function bitAnd($fieldLeft, $fieldRight) {
1260 return "($fieldLeft & $fieldRight)";
1261 }
1262
1263 function bitOr($fieldLeft, $fieldRight) {
1264 return "($fieldLeft | $fieldRight)";
1265 }
1266
1267 /**
1268 * Change the current database
1269 *
1270 * @return bool Success or failure
1271 */
1272 function selectDB( $db ) {
1273 # Stub. Shouldn't cause serious problems if it's not overridden, but
1274 # if your database engine supports a concept similar to MySQL's
1275 # databases you may as well. TODO: explain what exactly will fail if
1276 # this is not overridden.
1277 return true;
1278 }
1279
1280 /**
1281 * Get the current DB name
1282 */
1283 function getDBname() {
1284 return $this->mDBname;
1285 }
1286
1287 /**
1288 * Get the server hostname or IP address
1289 */
1290 function getServer() {
1291 return $this->mServer;
1292 }
1293
1294 /**
1295 * Format a table name ready for use in constructing an SQL query
1296 *
1297 * This does two important things: it quotes the table names to clean them up,
1298 * and it adds a table prefix if only given a table name with no quotes.
1299 *
1300 * All functions of this object which require a table name call this function
1301 * themselves. Pass the canonical name to such functions. This is only needed
1302 * when calling query() directly.
1303 *
1304 * @param $name String: database table name
1305 * @return String: full database name
1306 */
1307 function tableName( $name ) {
1308 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1309 # Skip the entire process when we have a string quoted on both ends.
1310 # Note that we check the end so that we will still quote any use of
1311 # use of `database`.table. But won't break things if someone wants
1312 # to query a database table with a dot in the name.
1313 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1314
1315 # Lets test for any bits of text that should never show up in a table
1316 # name. Basically anything like JOIN or ON which are actually part of
1317 # SQL queries, but may end up inside of the table value to combine
1318 # sql. Such as how the API is doing.
1319 # Note that we use a whitespace test rather than a \b test to avoid
1320 # any remote case where a word like on may be inside of a table name
1321 # surrounded by symbols which may be considered word breaks.
1322 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1323
1324 # Split database and table into proper variables.
1325 # We reverse the explode so that database.table and table both output
1326 # the correct table.
1327 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1328 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
1329 else @list( $table ) = $dbDetails;
1330 $prefix = $this->mTablePrefix; # Default prefix
1331
1332 # A database name has been specified in input. Quote the table name
1333 # because we don't want any prefixes added.
1334 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1335
1336 # Note that we use the long format because php will complain in in_array if
1337 # the input is not an array, and will complain in is_array if it is not set.
1338 if( !isset( $database ) # Don't use shared database if pre selected.
1339 && isset( $wgSharedDB ) # We have a shared database
1340 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1341 && isset( $wgSharedTables )
1342 && is_array( $wgSharedTables )
1343 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1344 $database = $wgSharedDB;
1345 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1346 }
1347
1348 # Quote the $database and $table and apply the prefix if not quoted.
1349 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1350 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1351
1352 # Merge our database and table into our final table name.
1353 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1354
1355 # We're finished, return.
1356 return $tableName;
1357 }
1358
1359 /**
1360 * Fetch a number of table names into an array
1361 * This is handy when you need to construct SQL for joins
1362 *
1363 * Example:
1364 * extract($dbr->tableNames('user','watchlist'));
1365 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1366 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1367 */
1368 public function tableNames() {
1369 $inArray = func_get_args();
1370 $retVal = array();
1371 foreach ( $inArray as $name ) {
1372 $retVal[$name] = $this->tableName( $name );
1373 }
1374 return $retVal;
1375 }
1376
1377 /**
1378 * Fetch a number of table names into an zero-indexed numerical array
1379 * This is handy when you need to construct SQL for joins
1380 *
1381 * Example:
1382 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1383 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1384 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1385 */
1386 public function tableNamesN() {
1387 $inArray = func_get_args();
1388 $retVal = array();
1389 foreach ( $inArray as $name ) {
1390 $retVal[] = $this->tableName( $name );
1391 }
1392 return $retVal;
1393 }
1394
1395 /**
1396 * @private
1397 */
1398 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1399 $ret = array();
1400 $retJOIN = array();
1401 $use_index_safe = is_array($use_index) ? $use_index : array();
1402 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1403 foreach ( $tables as $table ) {
1404 // Is there a JOIN and INDEX clause for this table?
1405 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1406 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1407 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1408 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1409 $retJOIN[] = $tableClause;
1410 // Is there an INDEX clause?
1411 } else if ( isset($use_index_safe[$table]) ) {
1412 $tableClause = $this->tableName( $table );
1413 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1414 $ret[] = $tableClause;
1415 // Is there a JOIN clause?
1416 } else if ( isset($join_conds_safe[$table]) ) {
1417 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1418 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1419 $retJOIN[] = $tableClause;
1420 } else {
1421 $tableClause = $this->tableName( $table );
1422 $ret[] = $tableClause;
1423 }
1424 }
1425 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1426 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1427 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1428 // Compile our final table clause
1429 return implode(' ',array($straightJoins,$otherJoins) );
1430 }
1431
1432 /**
1433 * Get the name of an index in a given table
1434 */
1435 function indexName( $index ) {
1436 // Backwards-compatibility hack
1437 $renamed = array(
1438 'ar_usertext_timestamp' => 'usertext_timestamp',
1439 'un_user_id' => 'user_id',
1440 'un_user_ip' => 'user_ip',
1441 );
1442 if( isset( $renamed[$index] ) ) {
1443 return $renamed[$index];
1444 } else {
1445 return $index;
1446 }
1447 }
1448
1449 /**
1450 * Wrapper for addslashes()
1451 * @param $s String: to be slashed.
1452 * @return String: slashed string.
1453 */
1454 abstract function strencode( $s );
1455
1456 /**
1457 * If it's a string, adds quotes and backslashes
1458 * Otherwise returns as-is
1459 */
1460 function addQuotes( $s ) {
1461 if ( $s === null ) {
1462 return 'NULL';
1463 } else {
1464 # This will also quote numeric values. This should be harmless,
1465 # and protects against weird problems that occur when they really
1466 # _are_ strings such as article titles and string->number->string
1467 # conversion is not 1:1.
1468 return "'" . $this->strencode( $s ) . "'";
1469 }
1470 }
1471
1472 /**
1473 * Escape string for safe LIKE usage
1474 */
1475 function escapeLike( $s ) {
1476 $s=str_replace('\\','\\\\',$s);
1477 $s=$this->strencode( $s );
1478 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1479 return $s;
1480 }
1481
1482 /**
1483 * Returns an appropriately quoted sequence value for inserting a new row.
1484 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1485 * subclass will return an integer, and save the value for insertId()
1486 */
1487 function nextSequenceValue( $seqName ) {
1488 return NULL;
1489 }
1490
1491 /**
1492 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1493 * is only needed because a) MySQL must be as efficient as possible due to
1494 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1495 * which index to pick. Anyway, other databases might have different
1496 * indexes on a given table. So don't bother overriding this unless you're
1497 * MySQL.
1498 */
1499 function useIndexClause( $index ) {
1500 return '';
1501 }
1502
1503 /**
1504 * REPLACE query wrapper
1505 * PostgreSQL simulates this with a DELETE followed by INSERT
1506 * $row is the row to insert, an associative array
1507 * $uniqueIndexes is an array of indexes. Each element may be either a
1508 * field name or an array of field names
1509 *
1510 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1511 * However if you do this, you run the risk of encountering errors which wouldn't have
1512 * occurred in MySQL
1513 *
1514 * @todo migrate comment to phodocumentor format
1515 */
1516 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1517 $table = $this->tableName( $table );
1518
1519 # Single row case
1520 if ( !is_array( reset( $rows ) ) ) {
1521 $rows = array( $rows );
1522 }
1523
1524 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1525 $first = true;
1526 foreach ( $rows as $row ) {
1527 if ( $first ) {
1528 $first = false;
1529 } else {
1530 $sql .= ',';
1531 }
1532 $sql .= '(' . $this->makeList( $row ) . ')';
1533 }
1534 return $this->query( $sql, $fname );
1535 }
1536
1537 /**
1538 * DELETE where the condition is a join
1539 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1540 *
1541 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1542 * join condition matches, set $conds='*'
1543 *
1544 * DO NOT put the join condition in $conds
1545 *
1546 * @param $delTable String: The table to delete from.
1547 * @param $joinTable String: The other table.
1548 * @param $delVar String: The variable to join on, in the first table.
1549 * @param $joinVar String: The variable to join on, in the second table.
1550 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1551 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1552 */
1553 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1554 if ( !$conds ) {
1555 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1556 }
1557
1558 $delTable = $this->tableName( $delTable );
1559 $joinTable = $this->tableName( $joinTable );
1560 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1561 if ( $conds != '*' ) {
1562 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1563 }
1564
1565 return $this->query( $sql, $fname );
1566 }
1567
1568 /**
1569 * Returns the size of a text field, or -1 for "unlimited"
1570 */
1571 function textFieldSize( $table, $field ) {
1572 $table = $this->tableName( $table );
1573 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1574 $res = $this->query( $sql, 'Database::textFieldSize' );
1575 $row = $this->fetchObject( $res );
1576 $this->freeResult( $res );
1577
1578 $m = array();
1579 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1580 $size = $m[1];
1581 } else {
1582 $size = -1;
1583 }
1584 return $size;
1585 }
1586
1587 /**
1588 * A string to insert into queries to show that they're low-priority, like
1589 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1590 * string and nothing bad should happen.
1591 *
1592 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1593 */
1594 function lowPriorityOption() {
1595 return '';
1596 }
1597
1598 /**
1599 * DELETE query wrapper
1600 *
1601 * Use $conds == "*" to delete all rows
1602 */
1603 function delete( $table, $conds, $fname = 'Database::delete' ) {
1604 if ( !$conds ) {
1605 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1606 }
1607 $table = $this->tableName( $table );
1608 $sql = "DELETE FROM $table";
1609 if ( $conds != '*' ) {
1610 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1611 }
1612 return $this->query( $sql, $fname );
1613 }
1614
1615 /**
1616 * INSERT SELECT wrapper
1617 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1618 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1619 * $conds may be "*" to copy the whole table
1620 * srcTable may be an array of tables.
1621 */
1622 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1623 $insertOptions = array(), $selectOptions = array() )
1624 {
1625 $destTable = $this->tableName( $destTable );
1626 if ( is_array( $insertOptions ) ) {
1627 $insertOptions = implode( ' ', $insertOptions );
1628 }
1629 if( !is_array( $selectOptions ) ) {
1630 $selectOptions = array( $selectOptions );
1631 }
1632 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1633 if( is_array( $srcTable ) ) {
1634 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1635 } else {
1636 $srcTable = $this->tableName( $srcTable );
1637 }
1638 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1639 " SELECT $startOpts " . implode( ',', $varMap ) .
1640 " FROM $srcTable $useIndex ";
1641 if ( $conds != '*' ) {
1642 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1643 }
1644 $sql .= " $tailOpts";
1645 return $this->query( $sql, $fname );
1646 }
1647
1648 /**
1649 * Construct a LIMIT query with optional offset. This is used for query
1650 * pages. The SQL should be adjusted so that only the first $limit rows
1651 * are returned. If $offset is provided as well, then the first $offset
1652 * rows should be discarded, and the next $limit rows should be returned.
1653 * If the result of the query is not ordered, then the rows to be returned
1654 * are theoretically arbitrary.
1655 *
1656 * $sql is expected to be a SELECT, if that makes a difference. For
1657 * UPDATE, limitResultForUpdate should be used.
1658 *
1659 * The version provided by default works in MySQL and SQLite. It will very
1660 * likely need to be overridden for most other DBMSes.
1661 *
1662 * @param $sql String: SQL query we will append the limit too
1663 * @param $limit Integer: the SQL limit
1664 * @param $offset Integer the SQL offset (default false)
1665 */
1666 function limitResult( $sql, $limit, $offset=false ) {
1667 if( !is_numeric( $limit ) ) {
1668 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1669 }
1670 return "$sql LIMIT "
1671 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1672 . "{$limit} ";
1673 }
1674 function limitResultForUpdate( $sql, $num ) {
1675 return $this->limitResult( $sql, $num, 0 );
1676 }
1677
1678 /**
1679 * Construct a UNION query
1680 * This is used for providing overload point for other DB abstractions
1681 * not compatible with the MySQL syntax.
1682 * @param $sqls Array: SQL statements to combine
1683 * @param $all Boolean: use UNION ALL
1684 * @return String: SQL fragment
1685 */
1686 function unionQueries($sqls, $all) {
1687 $glue = $all ? ') UNION ALL (' : ') UNION (';
1688 return '('.implode( $glue, $sqls ) . ')';
1689 }
1690
1691 /**
1692 * Returns an SQL expression for a simple conditional. This doesn't need
1693 * to be overridden unless CASE isn't supported in your DBMS.
1694 *
1695 * @param $cond String: SQL expression which will result in a boolean value
1696 * @param $trueVal String: SQL expression to return if true
1697 * @param $falseVal String: SQL expression to return if false
1698 * @return String: SQL fragment
1699 */
1700 function conditional( $cond, $trueVal, $falseVal ) {
1701 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1702 }
1703
1704 /**
1705 * Returns a comand for str_replace function in SQL query.
1706 * Uses REPLACE() in MySQL
1707 *
1708 * @param $orig String: column to modify
1709 * @param $old String: column to seek
1710 * @param $new String: column to replace with
1711 */
1712 function strreplace( $orig, $old, $new ) {
1713 return "REPLACE({$orig}, {$old}, {$new})";
1714 }
1715
1716 /**
1717 * Determines if the last failure was due to a deadlock
1718 */
1719 function wasDeadlock() {
1720 return $this->lastErrno() == 1213;
1721 }
1722
1723 /**
1724 * Determines if the last query error was something that should be dealt
1725 * with by pinging the connection and reissuing the query
1726 */
1727 function wasErrorReissuable() {
1728 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1729 }
1730
1731 /**
1732 * Perform a deadlock-prone transaction.
1733 *
1734 * This function invokes a callback function to perform a set of write
1735 * queries. If a deadlock occurs during the processing, the transaction
1736 * will be rolled back and the callback function will be called again.
1737 *
1738 * Usage:
1739 * $dbw->deadlockLoop( callback, ... );
1740 *
1741 * Extra arguments are passed through to the specified callback function.
1742 *
1743 * Returns whatever the callback function returned on its successful,
1744 * iteration, or false on error, for example if the retry limit was
1745 * reached.
1746 */
1747 function deadlockLoop() {
1748 $myFname = 'Database::deadlockLoop';
1749
1750 $this->begin();
1751 $args = func_get_args();
1752 $function = array_shift( $args );
1753 $oldIgnore = $this->ignoreErrors( true );
1754 $tries = DEADLOCK_TRIES;
1755 if ( is_array( $function ) ) {
1756 $fname = $function[0];
1757 } else {
1758 $fname = $function;
1759 }
1760 do {
1761 $retVal = call_user_func_array( $function, $args );
1762 $error = $this->lastError();
1763 $errno = $this->lastErrno();
1764 $sql = $this->lastQuery();
1765
1766 if ( $errno ) {
1767 if ( $this->wasDeadlock() ) {
1768 # Retry
1769 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1770 } else {
1771 $this->reportQueryError( $error, $errno, $sql, $fname );
1772 }
1773 }
1774 } while( $this->wasDeadlock() && --$tries > 0 );
1775 $this->ignoreErrors( $oldIgnore );
1776 if ( $tries <= 0 ) {
1777 $this->query( 'ROLLBACK', $myFname );
1778 $this->reportQueryError( $error, $errno, $sql, $fname );
1779 return false;
1780 } else {
1781 $this->query( 'COMMIT', $myFname );
1782 return $retVal;
1783 }
1784 }
1785
1786 /**
1787 * Do a SELECT MASTER_POS_WAIT()
1788 *
1789 * @param $pos MySQLMasterPos object
1790 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1791 */
1792 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1793 $fname = 'Database::masterPosWait';
1794 wfProfileIn( $fname );
1795
1796 # Commit any open transactions
1797 if ( $this->mTrxLevel ) {
1798 $this->immediateCommit();
1799 }
1800
1801 if ( !is_null( $this->mFakeSlaveLag ) ) {
1802 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1803 if ( $wait > $timeout * 1e6 ) {
1804 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1805 wfProfileOut( $fname );
1806 return -1;
1807 } elseif ( $wait > 0 ) {
1808 wfDebug( "Fake slave waiting $wait us\n" );
1809 usleep( $wait );
1810 wfProfileOut( $fname );
1811 return 1;
1812 } else {
1813 wfDebug( "Fake slave up to date ($wait us)\n" );
1814 wfProfileOut( $fname );
1815 return 0;
1816 }
1817 }
1818
1819 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1820 $encFile = $this->addQuotes( $pos->file );
1821 $encPos = intval( $pos->pos );
1822 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1823 $res = $this->doQuery( $sql );
1824 if ( $res && $row = $this->fetchRow( $res ) ) {
1825 $this->freeResult( $res );
1826 wfProfileOut( $fname );
1827 return $row[0];
1828 } else {
1829 wfProfileOut( $fname );
1830 return false;
1831 }
1832 }
1833
1834 /**
1835 * Get the position of the master from SHOW SLAVE STATUS
1836 */
1837 function getSlavePos() {
1838 if ( !is_null( $this->mFakeSlaveLag ) ) {
1839 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1840 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1841 return $pos;
1842 }
1843 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1844 $row = $this->fetchObject( $res );
1845 if ( $row ) {
1846 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1847 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1848 } else {
1849 return false;
1850 }
1851 }
1852
1853 /**
1854 * Get the position of the master from SHOW MASTER STATUS
1855 */
1856 function getMasterPos() {
1857 if ( $this->mFakeMaster ) {
1858 return new MySQLMasterPos( 'fake', microtime( true ) );
1859 }
1860 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1861 $row = $this->fetchObject( $res );
1862 if ( $row ) {
1863 return new MySQLMasterPos( $row->File, $row->Position );
1864 } else {
1865 return false;
1866 }
1867 }
1868
1869 /**
1870 * Begin a transaction, committing any previously open transaction
1871 */
1872 function begin( $fname = 'Database::begin' ) {
1873 $this->query( 'BEGIN', $fname );
1874 $this->mTrxLevel = 1;
1875 }
1876
1877 /**
1878 * End a transaction
1879 */
1880 function commit( $fname = 'Database::commit' ) {
1881 $this->query( 'COMMIT', $fname );
1882 $this->mTrxLevel = 0;
1883 }
1884
1885 /**
1886 * Rollback a transaction.
1887 * No-op on non-transactional databases.
1888 */
1889 function rollback( $fname = 'Database::rollback' ) {
1890 $this->query( 'ROLLBACK', $fname, true );
1891 $this->mTrxLevel = 0;
1892 }
1893
1894 /**
1895 * Begin a transaction, committing any previously open transaction
1896 * @deprecated use begin()
1897 */
1898 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1899 $this->begin();
1900 }
1901
1902 /**
1903 * Commit transaction, if one is open
1904 * @deprecated use commit()
1905 */
1906 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1907 $this->commit();
1908 }
1909
1910 /**
1911 * Return MW-style timestamp used for MySQL schema
1912 */
1913 function timestamp( $ts=0 ) {
1914 return wfTimestamp(TS_MW,$ts);
1915 }
1916
1917 /**
1918 * Local database timestamp format or null
1919 */
1920 function timestampOrNull( $ts = null ) {
1921 if( is_null( $ts ) ) {
1922 return null;
1923 } else {
1924 return $this->timestamp( $ts );
1925 }
1926 }
1927
1928 /**
1929 * @todo document
1930 */
1931 function resultObject( $result ) {
1932 if( empty( $result ) ) {
1933 return false;
1934 } elseif ( $result instanceof ResultWrapper ) {
1935 return $result;
1936 } elseif ( $result === true ) {
1937 // Successful write query
1938 return $result;
1939 } else {
1940 return new ResultWrapper( $this, $result );
1941 }
1942 }
1943
1944 /**
1945 * Return aggregated value alias
1946 */
1947 function aggregateValue ($valuedata,$valuename='value') {
1948 return $valuename;
1949 }
1950
1951 /**
1952 * Returns a wikitext link to the DB's website, e.g.,
1953 * return "[http://www.mysql.com/ MySQL]";
1954 * Should at least contain plain text, if for some reason
1955 * your database has no website.
1956 *
1957 * @return String: wikitext of a link to the server software's web site
1958 */
1959 abstract function getSoftwareLink();
1960
1961 /**
1962 * Returns the database type for user-visible purposes
1963 * e.g. DB error messages
1964 * Other uses should just use $wgDBtype
1965 *
1966 * @return String: Database type for use in messages
1967 */
1968 abstract function getDBtypeForMsg();
1969
1970 /**
1971 * A string describing the current software version, like from
1972 * mysql_get_server_info(). Will be listed on Special:Version, etc.
1973 *
1974 * @return String: Version information from the database
1975 */
1976 abstract function getServerVersion();
1977
1978 /**
1979 * Ping the server and try to reconnect if it there is no connection
1980 *
1981 * @return bool Success or failure
1982 */
1983 function ping() {
1984 # Stub. Not essential to override.
1985 return true;
1986 }
1987
1988 /**
1989 * Get slave lag.
1990 * At the moment, this will only work if the DB user has the PROCESS privilege
1991 */
1992 function getLag() {
1993 if ( !is_null( $this->mFakeSlaveLag ) ) {
1994 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
1995 return $this->mFakeSlaveLag;
1996 }
1997 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
1998 # Find slave SQL thread
1999 while ( $row = $this->fetchObject( $res ) ) {
2000 /* This should work for most situations - when default db
2001 * for thread is not specified, it had no events executed,
2002 * and therefore it doesn't know yet how lagged it is.
2003 *
2004 * Relay log I/O thread does not select databases.
2005 */
2006 if ( $row->User == 'system user' &&
2007 $row->State != 'Waiting for master to send event' &&
2008 $row->State != 'Connecting to master' &&
2009 $row->State != 'Queueing master event to the relay log' &&
2010 $row->State != 'Waiting for master update' &&
2011 $row->State != 'Requesting binlog dump' &&
2012 $row->State != 'Waiting to reconnect after a failed master event read' &&
2013 $row->State != 'Reconnecting after a failed master event read' &&
2014 $row->State != 'Registering slave on master'
2015 ) {
2016 # This is it, return the time (except -ve)
2017 if ( $row->Time > 0x7fffffff ) {
2018 return false;
2019 } else {
2020 return $row->Time;
2021 }
2022 }
2023 }
2024 return false;
2025 }
2026
2027 /**
2028 * Get status information from SHOW STATUS in an associative array
2029 */
2030 function getStatus($which="%") {
2031 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2032 $status = array();
2033 while ( $row = $this->fetchObject( $res ) ) {
2034 $status[$row->Variable_name] = $row->Value;
2035 }
2036 return $status;
2037 }
2038
2039 /**
2040 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2041 */
2042 function maxListLen() {
2043 return 0;
2044 }
2045
2046 function encodeBlob($b) {
2047 return $b;
2048 }
2049
2050 function decodeBlob($b) {
2051 return $b;
2052 }
2053
2054 /**
2055 * Override database's default connection timeout. May be useful for very
2056 * long batch queries such as full-wiki dumps, where a single query reads
2057 * out over hours or days. May or may not be necessary for non-MySQL
2058 * databases. For most purposes, leaving it as a no-op should be fine.
2059 *
2060 * @param $timeout Integer in seconds
2061 */
2062 public function setTimeout( $timeout ) {}
2063
2064 /**
2065 * Read and execute SQL commands from a file.
2066 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2067 * @param $filename String: File name to open
2068 * @param $lineCallback Callback: Optional function called before reading each line
2069 * @param $resultCallback Callback: Optional function called for each MySQL result
2070 */
2071 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2072 $fp = fopen( $filename, 'r' );
2073 if ( false === $fp ) {
2074 throw new MWException( "Could not open \"{$filename}\".\n" );
2075 }
2076 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2077 fclose( $fp );
2078 return $error;
2079 }
2080
2081 /**
2082 * Get the full path of a patch file. Originally based on archive()
2083 * from updaters.inc. Keep in mind this always returns a patch, as
2084 * it fails back to MySQL if no DB-specific patch can be found
2085 *
2086 * @param $patch String The name of the patch, like patch-something.sql
2087 * @return String Full path to patch file
2088 */
2089 public static function patchPath( $patch ) {
2090 global $wgDBtype, $IP;
2091 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
2092 return "$IP/maintenance/$wgDBtype/archives/$name";
2093 } else {
2094 return "$IP/maintenance/archives/$name";
2095 }
2096 }
2097
2098 /**
2099 * Read and execute commands from an open file handle
2100 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2101 * @param $fp String: File handle
2102 * @param $lineCallback Callback: Optional function called before reading each line
2103 * @param $resultCallback Callback: Optional function called for each MySQL result
2104 */
2105 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2106 $cmd = "";
2107 $done = false;
2108 $dollarquote = false;
2109
2110 while ( ! feof( $fp ) ) {
2111 if ( $lineCallback ) {
2112 call_user_func( $lineCallback );
2113 }
2114 $line = trim( fgets( $fp, 1024 ) );
2115 $sl = strlen( $line ) - 1;
2116
2117 if ( $sl < 0 ) { continue; }
2118 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2119
2120 ## Allow dollar quoting for function declarations
2121 if (substr($line,0,4) == '$mw$') {
2122 if ($dollarquote) {
2123 $dollarquote = false;
2124 $done = true;
2125 }
2126 else {
2127 $dollarquote = true;
2128 }
2129 }
2130 else if (!$dollarquote) {
2131 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2132 $done = true;
2133 $line = substr( $line, 0, $sl );
2134 }
2135 }
2136
2137 if ( '' != $cmd ) { $cmd .= ' '; }
2138 $cmd .= "$line\n";
2139
2140 if ( $done ) {
2141 $cmd = str_replace(';;', ";", $cmd);
2142 $cmd = $this->replaceVars( $cmd );
2143 $res = $this->query( $cmd, __METHOD__ );
2144 if ( $resultCallback ) {
2145 call_user_func( $resultCallback, $res, $this );
2146 }
2147
2148 if ( false === $res ) {
2149 $err = $this->lastError();
2150 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2151 }
2152
2153 $cmd = '';
2154 $done = false;
2155 }
2156 }
2157 return true;
2158 }
2159
2160
2161 /**
2162 * Replace variables in sourced SQL
2163 */
2164 protected function replaceVars( $ins ) {
2165 $varnames = array(
2166 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2167 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2168 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2169 );
2170
2171 // Ordinary variables
2172 foreach ( $varnames as $var ) {
2173 if( isset( $GLOBALS[$var] ) ) {
2174 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2175 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2176 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2177 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2178 }
2179 }
2180
2181 // Table prefixes
2182 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2183 array( $this, 'tableNameCallback' ), $ins );
2184
2185 // Index names
2186 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2187 array( $this, 'indexNameCallback' ), $ins );
2188 return $ins;
2189 }
2190
2191 /**
2192 * Table name callback
2193 * @private
2194 */
2195 protected function tableNameCallback( $matches ) {
2196 return $this->tableName( $matches[1] );
2197 }
2198
2199 /**
2200 * Index name callback
2201 */
2202 protected function indexNameCallback( $matches ) {
2203 return $this->indexName( $matches[1] );
2204 }
2205
2206 /*
2207 * Build a concatenation list to feed into a SQL query
2208 */
2209 function buildConcat( $stringList ) {
2210 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2211 }
2212
2213 /**
2214 * Acquire a named lock
2215 *
2216 * Abstracted from Filestore::lock() so child classes can implement for
2217 * their own needs.
2218 *
2219 * @param $lockName String: Name of lock to aquire
2220 * @param $method String: Name of method calling us
2221 * @return bool
2222 */
2223 public function lock( $lockName, $method, $timeout = 5 ) {
2224 return true;
2225 }
2226
2227 /**
2228 * Release a lock.
2229 *
2230 * @param $lockName String: Name of lock to release
2231 * @param $method String: Name of method calling us
2232 *
2233 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2234 * @return Returns 1 if the lock was released, 0 if the lock was not established
2235 * by this thread (in which case the lock is not released), and NULL if the named
2236 * lock did not exist
2237 */
2238 public function unlock( $lockName, $method ) {
2239 return true;
2240 }
2241
2242 /**
2243 * Lock specific tables
2244 *
2245 * @param $read Array of tables to lock for read access
2246 * @param $write Array of tables to lock for write access
2247 * @param $method String name of caller
2248 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2249 */
2250 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2251 return true;
2252 }
2253
2254 /**
2255 * Unlock specific tables
2256 *
2257 * @param $method String the caller
2258 */
2259 public function unlockTables( $method ) {
2260 return true;
2261 }
2262
2263 /**
2264 * Get search engine class. All subclasses of this
2265 * need to implement this if they wish to use searching.
2266 *
2267 * @return String
2268 */
2269 public function getSearchEngine() {
2270 return "SearchMySQL";
2271 }
2272
2273 /**
2274 * Allow or deny "big selects" for this session only. This is done by setting
2275 * the sql_big_selects session variable.
2276 *
2277 * This is a MySQL-specific feature.
2278 *
2279 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2280 */
2281 public function setBigSelects( $value = true ) {
2282 // no-op
2283 }
2284 }
2285
2286
2287 /******************************************************************************
2288 * Utility classes
2289 *****************************************************************************/
2290
2291 /**
2292 * Utility class.
2293 * @ingroup Database
2294 */
2295 class DBObject {
2296 public $mData;
2297
2298 function DBObject($data) {
2299 $this->mData = $data;
2300 }
2301
2302 function isLOB() {
2303 return false;
2304 }
2305
2306 function data() {
2307 return $this->mData;
2308 }
2309 }
2310
2311 /**
2312 * Utility class
2313 * @ingroup Database
2314 *
2315 * This allows us to distinguish a blob from a normal string and an array of strings
2316 */
2317 class Blob {
2318 private $mData;
2319 function __construct($data) {
2320 $this->mData = $data;
2321 }
2322 function fetch() {
2323 return $this->mData;
2324 }
2325 }
2326
2327 /**
2328 * Utility class.
2329 * @ingroup Database
2330 */
2331 class MySQLField {
2332 private $name, $tablename, $default, $max_length, $nullable,
2333 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2334 function __construct ($info) {
2335 $this->name = $info->name;
2336 $this->tablename = $info->table;
2337 $this->default = $info->def;
2338 $this->max_length = $info->max_length;
2339 $this->nullable = !$info->not_null;
2340 $this->is_pk = $info->primary_key;
2341 $this->is_unique = $info->unique_key;
2342 $this->is_multiple = $info->multiple_key;
2343 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2344 $this->type = $info->type;
2345 }
2346
2347 function name() {
2348 return $this->name;
2349 }
2350
2351 function tableName() {
2352 return $this->tableName;
2353 }
2354
2355 function defaultValue() {
2356 return $this->default;
2357 }
2358
2359 function maxLength() {
2360 return $this->max_length;
2361 }
2362
2363 function nullable() {
2364 return $this->nullable;
2365 }
2366
2367 function isKey() {
2368 return $this->is_key;
2369 }
2370
2371 function isMultipleKey() {
2372 return $this->is_multiple;
2373 }
2374
2375 function type() {
2376 return $this->type;
2377 }
2378 }
2379
2380 /******************************************************************************
2381 * Error classes
2382 *****************************************************************************/
2383
2384 /**
2385 * Database error base class
2386 * @ingroup Database
2387 */
2388 class DBError extends MWException {
2389 public $db;
2390
2391 /**
2392 * Construct a database error
2393 * @param $db Database object which threw the error
2394 * @param $error A simple error message to be used for debugging
2395 */
2396 function __construct( DatabaseBase &$db, $error ) {
2397 $this->db =& $db;
2398 parent::__construct( $error );
2399 }
2400 }
2401
2402 /**
2403 * @ingroup Database
2404 */
2405 class DBConnectionError extends DBError {
2406 public $error;
2407
2408 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2409 $msg = 'DB connection error';
2410 if ( trim( $error ) != '' ) {
2411 $msg .= ": $error";
2412 }
2413 $this->error = $error;
2414 parent::__construct( $db, $msg );
2415 }
2416
2417 function useOutputPage() {
2418 // Not likely to work
2419 return false;
2420 }
2421
2422 function useMessageCache() {
2423 // Not likely to work
2424 return false;
2425 }
2426
2427 function getText() {
2428 return $this->getMessage() . "\n";
2429 }
2430
2431 function getLogMessage() {
2432 # Don't send to the exception log
2433 return false;
2434 }
2435
2436 function getPageTitle() {
2437 global $wgSitename, $wgLang;
2438 $header = "$wgSitename has a problem";
2439 if ( $wgLang instanceof Language ) {
2440 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2441 }
2442
2443 return $header;
2444 }
2445
2446 function getHTML() {
2447 global $wgLang, $wgMessageCache, $wgUseFileCache;
2448
2449 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2450 $again = 'Try waiting a few minutes and reloading.';
2451 $info = '(Can\'t contact the database server: $1)';
2452
2453 if ( $wgLang instanceof Language ) {
2454 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2455 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2456 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2457 }
2458
2459 # No database access
2460 if ( is_object( $wgMessageCache ) ) {
2461 $wgMessageCache->disable();
2462 }
2463
2464 if ( trim( $this->error ) == '' ) {
2465 $this->error = $this->db->getProperty('mServer');
2466 }
2467
2468 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2469 $text = str_replace( '$1', $this->error, $noconnect );
2470
2471 /*
2472 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2473 $text .= '</p><p>Backtrace:</p><p>' .
2474 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2475 "</p>\n";
2476 }*/
2477
2478 $extra = $this->searchForm();
2479
2480 if( $wgUseFileCache ) {
2481 try {
2482 $cache = $this->fileCachedPage();
2483 # Cached version on file system?
2484 if( $cache !== null ) {
2485 # Hack: extend the body for error messages
2486 $cache = str_replace( array('</html>','</body>'), '', $cache );
2487 # Add cache notice...
2488 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2489 # Localize it if possible...
2490 if( $wgLang instanceof Language ) {
2491 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2492 }
2493 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2494 # Output cached page with notices on bottom and re-close body
2495 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2496 }
2497 } catch( MWException $e ) {
2498 // Do nothing, just use the default page
2499 }
2500 }
2501 # Headers needed here - output is just the error message
2502 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2503 }
2504
2505 function searchForm() {
2506 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2507 $usegoogle = "You can try searching via Google in the meantime.";
2508 $outofdate = "Note that their indexes of our content may be out of date.";
2509 $googlesearch = "Search";
2510
2511 if ( $wgLang instanceof Language ) {
2512 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2513 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2514 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2515 }
2516
2517 $search = htmlspecialchars(@$_REQUEST['search']);
2518
2519 $trygoogle = <<<EOT
2520 <div style="margin: 1.5em">$usegoogle<br />
2521 <small>$outofdate</small></div>
2522 <!-- SiteSearch Google -->
2523 <form method="get" action="http://www.google.com/search" id="googlesearch">
2524 <input type="hidden" name="domains" value="$wgServer" />
2525 <input type="hidden" name="num" value="50" />
2526 <input type="hidden" name="ie" value="$wgInputEncoding" />
2527 <input type="hidden" name="oe" value="$wgInputEncoding" />
2528
2529 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2530
2531 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2532 <input type="submit" name="btnG" value="$googlesearch" />
2533 <div>
2534 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2535 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2536 </div>
2537 </form>
2538 <!-- SiteSearch Google -->
2539 EOT;
2540 return $trygoogle;
2541 }
2542
2543 function fileCachedPage() {
2544 global $wgTitle, $title, $wgLang, $wgOut;
2545 if( $wgOut->isDisabled() ) return; // Done already?
2546 $mainpage = 'Main Page';
2547 if ( $wgLang instanceof Language ) {
2548 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2549 }
2550
2551 if( $wgTitle ) {
2552 $t =& $wgTitle;
2553 } elseif( $title ) {
2554 $t = Title::newFromURL( $title );
2555 } else {
2556 $t = Title::newFromText( $mainpage );
2557 }
2558
2559 $cache = new HTMLFileCache( $t );
2560 if( $cache->isFileCached() ) {
2561 return $cache->fetchPageText();
2562 } else {
2563 return '';
2564 }
2565 }
2566
2567 function htmlBodyOnly() {
2568 return true;
2569 }
2570
2571 }
2572
2573 /**
2574 * @ingroup Database
2575 */
2576 class DBQueryError extends DBError {
2577 public $error, $errno, $sql, $fname;
2578
2579 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2580 $message = "A database error has occurred\n" .
2581 "Query: $sql\n" .
2582 "Function: $fname\n" .
2583 "Error: $errno $error\n";
2584
2585 parent::__construct( $db, $message );
2586 $this->error = $error;
2587 $this->errno = $errno;
2588 $this->sql = $sql;
2589 $this->fname = $fname;
2590 }
2591
2592 function getText() {
2593 if ( $this->useMessageCache() ) {
2594 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2595 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ),
2596 htmlspecialchars( $this->db->getDBtypeForMsg() ) ) . "\n";
2597 } else {
2598 return $this->getMessage();
2599 }
2600 }
2601
2602 function getSQL() {
2603 global $wgShowSQLErrors;
2604 if( !$wgShowSQLErrors ) {
2605 return $this->msg( 'sqlhidden', 'SQL hidden' );
2606 } else {
2607 return $this->sql;
2608 }
2609 }
2610
2611 function getLogMessage() {
2612 # Don't send to the exception log
2613 return false;
2614 }
2615
2616 function getPageTitle() {
2617 return $this->msg( 'databaseerror', 'Database error' );
2618 }
2619
2620 function getHTML() {
2621 if ( $this->useMessageCache() ) {
2622 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2623 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ),
2624 htmlspecialchars( $this->db->getDBtypeForMsg() ) );
2625 } else {
2626 return nl2br( htmlspecialchars( $this->getMessage() ) );
2627 }
2628 }
2629 }
2630
2631 /**
2632 * @ingroup Database
2633 */
2634 class DBUnexpectedError extends DBError {}
2635
2636
2637 /**
2638 * Result wrapper for grabbing data queried by someone else
2639 * @ingroup Database
2640 */
2641 class ResultWrapper implements Iterator {
2642 var $db, $result, $pos = 0, $currentRow = null;
2643
2644 /**
2645 * Create a new result object from a result resource and a Database object
2646 */
2647 function ResultWrapper( $database, $result ) {
2648 $this->db = $database;
2649 if ( $result instanceof ResultWrapper ) {
2650 $this->result = $result->result;
2651 } else {
2652 $this->result = $result;
2653 }
2654 }
2655
2656 /**
2657 * Get the number of rows in a result object
2658 */
2659 function numRows() {
2660 return $this->db->numRows( $this );
2661 }
2662
2663 /**
2664 * Fetch the next row from the given result object, in object form.
2665 * Fields can be retrieved with $row->fieldname, with fields acting like
2666 * member variables.
2667 *
2668 * @param $res SQL result object as returned from Database::query(), etc.
2669 * @return MySQL row object
2670 * @throws DBUnexpectedError Thrown if the database returns an error
2671 */
2672 function fetchObject() {
2673 return $this->db->fetchObject( $this );
2674 }
2675
2676 /**
2677 * Fetch the next row from the given result object, in associative array
2678 * form. Fields are retrieved with $row['fieldname'].
2679 *
2680 * @param $res SQL result object as returned from Database::query(), etc.
2681 * @return MySQL row object
2682 * @throws DBUnexpectedError Thrown if the database returns an error
2683 */
2684 function fetchRow() {
2685 return $this->db->fetchRow( $this );
2686 }
2687
2688 /**
2689 * Free a result object
2690 */
2691 function free() {
2692 $this->db->freeResult( $this );
2693 unset( $this->result );
2694 unset( $this->db );
2695 }
2696
2697 /**
2698 * Change the position of the cursor in a result object
2699 * See mysql_data_seek()
2700 */
2701 function seek( $row ) {
2702 $this->db->dataSeek( $this, $row );
2703 }
2704
2705 /*********************
2706 * Iterator functions
2707 * Note that using these in combination with the non-iterator functions
2708 * above may cause rows to be skipped or repeated.
2709 */
2710
2711 function rewind() {
2712 if ($this->numRows()) {
2713 $this->db->dataSeek($this, 0);
2714 }
2715 $this->pos = 0;
2716 $this->currentRow = null;
2717 }
2718
2719 function current() {
2720 if ( is_null( $this->currentRow ) ) {
2721 $this->next();
2722 }
2723 return $this->currentRow;
2724 }
2725
2726 function key() {
2727 return $this->pos;
2728 }
2729
2730 function next() {
2731 $this->pos++;
2732 $this->currentRow = $this->fetchObject();
2733 return $this->currentRow;
2734 }
2735
2736 function valid() {
2737 return $this->current() !== false;
2738 }
2739 }