Spacing and declare public.
[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 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
945 $options['EXPLAIN'] = true;
946 $res = $this->select( $table, $vars, $conds, $fname, $options );
947 if ( $res === false )
948 return false;
949 if ( !$this->numRows( $res ) ) {
950 $this->freeResult($res);
951 return 0;
952 }
953
954 $rows = 1;
955 while( $plan = $this->fetchObject( $res ) ) {
956 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
957 }
958
959 $this->freeResult($res);
960 return $rows;
961 }
962
963 /**
964 * Removes most variables from an SQL query and replaces them with X or N for numbers.
965 * It's only slightly flawed. Don't use for anything important.
966 *
967 * @param $sql String: A SQL Query
968 */
969 static function generalizeSQL( $sql ) {
970 # This does the same as the regexp below would do, but in such a way
971 # as to avoid crashing php on some large strings.
972 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
973
974 $sql = str_replace ( "\\\\", '', $sql);
975 $sql = str_replace ( "\\'", '', $sql);
976 $sql = str_replace ( "\\\"", '', $sql);
977 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
978 $sql = preg_replace ('/".*"/s', "'X'", $sql);
979
980 # All newlines, tabs, etc replaced by single space
981 $sql = preg_replace ( '/\s+/', ' ', $sql);
982
983 # All numbers => N
984 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
985
986 return $sql;
987 }
988
989 /**
990 * Determines whether a field exists in a table
991 * Usually aborts on failure
992 * If errors are explicitly ignored, returns NULL on failure
993 */
994 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
995 $table = $this->tableName( $table );
996 $res = $this->query( 'DESCRIBE '.$table, $fname );
997 if ( !$res ) {
998 return NULL;
999 }
1000
1001 $found = false;
1002
1003 while ( $row = $this->fetchObject( $res ) ) {
1004 if ( $row->Field == $field ) {
1005 $found = true;
1006 break;
1007 }
1008 }
1009 return $found;
1010 }
1011
1012 /**
1013 * Determines whether an index exists
1014 * Usually aborts on failure
1015 * If errors are explicitly ignored, returns NULL on failure
1016 */
1017 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1018 $info = $this->indexInfo( $table, $index, $fname );
1019 if ( is_null( $info ) ) {
1020 return NULL;
1021 } else {
1022 return $info !== false;
1023 }
1024 }
1025
1026
1027 /**
1028 * Get information about an index into an object
1029 * Returns false if the index does not exist
1030 */
1031 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1032 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1033 # SHOW INDEX should work for 3.x and up:
1034 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1035 $table = $this->tableName( $table );
1036 $index = $this->indexName( $index );
1037 $sql = 'SHOW INDEX FROM '.$table;
1038 $res = $this->query( $sql, $fname );
1039 if ( !$res ) {
1040 return NULL;
1041 }
1042
1043 $result = array();
1044 while ( $row = $this->fetchObject( $res ) ) {
1045 if ( $row->Key_name == $index ) {
1046 $result[] = $row;
1047 }
1048 }
1049 $this->freeResult($res);
1050
1051 return empty($result) ? false : $result;
1052 }
1053
1054 /**
1055 * Query whether a given table exists
1056 */
1057 function tableExists( $table ) {
1058 $table = $this->tableName( $table );
1059 $old = $this->ignoreErrors( true );
1060 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1061 $this->ignoreErrors( $old );
1062 if( $res ) {
1063 $this->freeResult( $res );
1064 return true;
1065 } else {
1066 return false;
1067 }
1068 }
1069
1070 /**
1071 * mysql_fetch_field() wrapper
1072 * Returns false if the field doesn't exist
1073 *
1074 * @param $table
1075 * @param $field
1076 */
1077 abstract function fieldInfo( $table, $field );
1078
1079 /**
1080 * mysql_field_type() wrapper
1081 */
1082 function fieldType( $res, $index ) {
1083 if ( $res instanceof ResultWrapper ) {
1084 $res = $res->result;
1085 }
1086 return mysql_field_type( $res, $index );
1087 }
1088
1089 /**
1090 * Determines if a given index is unique
1091 */
1092 function indexUnique( $table, $index ) {
1093 $indexInfo = $this->indexInfo( $table, $index );
1094 if ( !$indexInfo ) {
1095 return NULL;
1096 }
1097 return !$indexInfo[0]->Non_unique;
1098 }
1099
1100 /**
1101 * INSERT wrapper, inserts an array into a table
1102 *
1103 * $a may be a single associative array, or an array of these with numeric keys, for
1104 * multi-row insert.
1105 *
1106 * Usually aborts on failure
1107 * If errors are explicitly ignored, returns success
1108 */
1109 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1110 # No rows to insert, easy just return now
1111 if ( !count( $a ) ) {
1112 return true;
1113 }
1114
1115 $table = $this->tableName( $table );
1116 if ( !is_array( $options ) ) {
1117 $options = array( $options );
1118 }
1119 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1120 $multi = true;
1121 $keys = array_keys( $a[0] );
1122 } else {
1123 $multi = false;
1124 $keys = array_keys( $a );
1125 }
1126
1127 $sql = 'INSERT ' . implode( ' ', $options ) .
1128 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1129
1130 if ( $multi ) {
1131 $first = true;
1132 foreach ( $a as $row ) {
1133 if ( $first ) {
1134 $first = false;
1135 } else {
1136 $sql .= ',';
1137 }
1138 $sql .= '(' . $this->makeList( $row ) . ')';
1139 }
1140 } else {
1141 $sql .= '(' . $this->makeList( $a ) . ')';
1142 }
1143 return (bool)$this->query( $sql, $fname );
1144 }
1145
1146 /**
1147 * Make UPDATE options for the Database::update function
1148 *
1149 * @private
1150 * @param $options Array: The options passed to Database::update
1151 * @return string
1152 */
1153 function makeUpdateOptions( $options ) {
1154 if( !is_array( $options ) ) {
1155 $options = array( $options );
1156 }
1157 $opts = array();
1158 if ( in_array( 'LOW_PRIORITY', $options ) )
1159 $opts[] = $this->lowPriorityOption();
1160 if ( in_array( 'IGNORE', $options ) )
1161 $opts[] = 'IGNORE';
1162 return implode(' ', $opts);
1163 }
1164
1165 /**
1166 * UPDATE wrapper, takes a condition array and a SET array
1167 *
1168 * @param $table String: The table to UPDATE
1169 * @param $values Array: An array of values to SET
1170 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1171 * @param $fname String: The Class::Function calling this function
1172 * (for the log)
1173 * @param $options Array: An array of UPDATE options, can be one or
1174 * more of IGNORE, LOW_PRIORITY
1175 * @return Boolean
1176 */
1177 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1178 $table = $this->tableName( $table );
1179 $opts = $this->makeUpdateOptions( $options );
1180 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1181 if ( $conds != '*' ) {
1182 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1183 }
1184 return $this->query( $sql, $fname );
1185 }
1186
1187 /**
1188 * Makes an encoded list of strings from an array
1189 * $mode:
1190 * LIST_COMMA - comma separated, no field names
1191 * LIST_AND - ANDed WHERE clause (without the WHERE)
1192 * LIST_OR - ORed WHERE clause (without the WHERE)
1193 * LIST_SET - comma separated with field names, like a SET clause
1194 * LIST_NAMES - comma separated field names
1195 */
1196 function makeList( $a, $mode = LIST_COMMA ) {
1197 if ( !is_array( $a ) ) {
1198 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1199 }
1200
1201 $first = true;
1202 $list = '';
1203 foreach ( $a as $field => $value ) {
1204 if ( !$first ) {
1205 if ( $mode == LIST_AND ) {
1206 $list .= ' AND ';
1207 } elseif($mode == LIST_OR) {
1208 $list .= ' OR ';
1209 } else {
1210 $list .= ',';
1211 }
1212 } else {
1213 $first = false;
1214 }
1215 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1216 $list .= "($value)";
1217 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1218 $list .= "$value";
1219 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1220 if( count( $value ) == 0 ) {
1221 throw new MWException( __METHOD__.': empty input' );
1222 } elseif( count( $value ) == 1 ) {
1223 // Special-case single values, as IN isn't terribly efficient
1224 // Don't necessarily assume the single key is 0; we don't
1225 // enforce linear numeric ordering on other arrays here.
1226 $value = array_values( $value );
1227 $list .= $field." = ".$this->addQuotes( $value[0] );
1228 } else {
1229 $list .= $field." IN (".$this->makeList($value).") ";
1230 }
1231 } elseif( $value === null ) {
1232 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1233 $list .= "$field IS ";
1234 } elseif ( $mode == LIST_SET ) {
1235 $list .= "$field = ";
1236 }
1237 $list .= 'NULL';
1238 } else {
1239 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1240 $list .= "$field = ";
1241 }
1242 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1243 }
1244 }
1245 return $list;
1246 }
1247
1248 /**
1249 * Bitwise operations
1250 */
1251
1252 function bitNot($field) {
1253 return "(~$bitField)";
1254 }
1255
1256 function bitAnd($fieldLeft, $fieldRight) {
1257 return "($fieldLeft & $fieldRight)";
1258 }
1259
1260 function bitOr($fieldLeft, $fieldRight) {
1261 return "($fieldLeft | $fieldRight)";
1262 }
1263
1264 /**
1265 * Change the current database
1266 *
1267 * @return bool Success or failure
1268 */
1269 function selectDB( $db ) {
1270 # Stub. Shouldn't cause serious problems if it's not overridden, but
1271 # if your database engine supports a concept similar to MySQL's
1272 # databases you may as well. TODO: explain what exactly will fail if
1273 # this is not overridden.
1274 return true;
1275 }
1276
1277 /**
1278 * Get the current DB name
1279 */
1280 function getDBname() {
1281 return $this->mDBname;
1282 }
1283
1284 /**
1285 * Get the server hostname or IP address
1286 */
1287 function getServer() {
1288 return $this->mServer;
1289 }
1290
1291 /**
1292 * Format a table name ready for use in constructing an SQL query
1293 *
1294 * This does two important things: it quotes the table names to clean them up,
1295 * and it adds a table prefix if only given a table name with no quotes.
1296 *
1297 * All functions of this object which require a table name call this function
1298 * themselves. Pass the canonical name to such functions. This is only needed
1299 * when calling query() directly.
1300 *
1301 * @param $name String: database table name
1302 * @return String: full database name
1303 */
1304 function tableName( $name ) {
1305 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1306 # Skip the entire process when we have a string quoted on both ends.
1307 # Note that we check the end so that we will still quote any use of
1308 # use of `database`.table. But won't break things if someone wants
1309 # to query a database table with a dot in the name.
1310 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1311
1312 # Lets test for any bits of text that should never show up in a table
1313 # name. Basically anything like JOIN or ON which are actually part of
1314 # SQL queries, but may end up inside of the table value to combine
1315 # sql. Such as how the API is doing.
1316 # Note that we use a whitespace test rather than a \b test to avoid
1317 # any remote case where a word like on may be inside of a table name
1318 # surrounded by symbols which may be considered word breaks.
1319 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1320
1321 # Split database and table into proper variables.
1322 # We reverse the explode so that database.table and table both output
1323 # the correct table.
1324 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1325 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
1326 else @list( $table ) = $dbDetails;
1327 $prefix = $this->mTablePrefix; # Default prefix
1328
1329 # A database name has been specified in input. Quote the table name
1330 # because we don't want any prefixes added.
1331 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1332
1333 # Note that we use the long format because php will complain in in_array if
1334 # the input is not an array, and will complain in is_array if it is not set.
1335 if( !isset( $database ) # Don't use shared database if pre selected.
1336 && isset( $wgSharedDB ) # We have a shared database
1337 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1338 && isset( $wgSharedTables )
1339 && is_array( $wgSharedTables )
1340 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1341 $database = $wgSharedDB;
1342 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1343 }
1344
1345 # Quote the $database and $table and apply the prefix if not quoted.
1346 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1347 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1348
1349 # Merge our database and table into our final table name.
1350 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1351
1352 # We're finished, return.
1353 return $tableName;
1354 }
1355
1356 /**
1357 * Fetch a number of table names into an array
1358 * This is handy when you need to construct SQL for joins
1359 *
1360 * Example:
1361 * extract($dbr->tableNames('user','watchlist'));
1362 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1363 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1364 */
1365 public function tableNames() {
1366 $inArray = func_get_args();
1367 $retVal = array();
1368 foreach ( $inArray as $name ) {
1369 $retVal[$name] = $this->tableName( $name );
1370 }
1371 return $retVal;
1372 }
1373
1374 /**
1375 * Fetch a number of table names into an zero-indexed numerical array
1376 * This is handy when you need to construct SQL for joins
1377 *
1378 * Example:
1379 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1380 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1381 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1382 */
1383 public function tableNamesN() {
1384 $inArray = func_get_args();
1385 $retVal = array();
1386 foreach ( $inArray as $name ) {
1387 $retVal[] = $this->tableName( $name );
1388 }
1389 return $retVal;
1390 }
1391
1392 /**
1393 * @private
1394 */
1395 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1396 $ret = array();
1397 $retJOIN = array();
1398 $use_index_safe = is_array($use_index) ? $use_index : array();
1399 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1400 foreach ( $tables as $table ) {
1401 // Is there a JOIN and INDEX clause for this table?
1402 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1403 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1404 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1405 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1406 $retJOIN[] = $tableClause;
1407 // Is there an INDEX clause?
1408 } else if ( isset($use_index_safe[$table]) ) {
1409 $tableClause = $this->tableName( $table );
1410 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1411 $ret[] = $tableClause;
1412 // Is there a JOIN clause?
1413 } else if ( isset($join_conds_safe[$table]) ) {
1414 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1415 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1416 $retJOIN[] = $tableClause;
1417 } else {
1418 $tableClause = $this->tableName( $table );
1419 $ret[] = $tableClause;
1420 }
1421 }
1422 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1423 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1424 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1425 // Compile our final table clause
1426 return implode(' ',array($straightJoins,$otherJoins) );
1427 }
1428
1429 /**
1430 * Get the name of an index in a given table
1431 */
1432 function indexName( $index ) {
1433 // Backwards-compatibility hack
1434 $renamed = array(
1435 'ar_usertext_timestamp' => 'usertext_timestamp',
1436 'un_user_id' => 'user_id',
1437 'un_user_ip' => 'user_ip',
1438 );
1439 if( isset( $renamed[$index] ) ) {
1440 return $renamed[$index];
1441 } else {
1442 return $index;
1443 }
1444 }
1445
1446 /**
1447 * Wrapper for addslashes()
1448 * @param $s String: to be slashed.
1449 * @return String: slashed string.
1450 */
1451 abstract function strencode( $s );
1452
1453 /**
1454 * If it's a string, adds quotes and backslashes
1455 * Otherwise returns as-is
1456 */
1457 function addQuotes( $s ) {
1458 if ( $s === null ) {
1459 return 'NULL';
1460 } else {
1461 # This will also quote numeric values. This should be harmless,
1462 # and protects against weird problems that occur when they really
1463 # _are_ strings such as article titles and string->number->string
1464 # conversion is not 1:1.
1465 return "'" . $this->strencode( $s ) . "'";
1466 }
1467 }
1468
1469 /**
1470 * Escape string for safe LIKE usage
1471 */
1472 function escapeLike( $s ) {
1473 $s=str_replace('\\','\\\\',$s);
1474 $s=$this->strencode( $s );
1475 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1476 return $s;
1477 }
1478
1479 /**
1480 * Returns an appropriately quoted sequence value for inserting a new row.
1481 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1482 * subclass will return an integer, and save the value for insertId()
1483 */
1484 function nextSequenceValue( $seqName ) {
1485 return NULL;
1486 }
1487
1488 /**
1489 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1490 * is only needed because a) MySQL must be as efficient as possible due to
1491 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1492 * which index to pick. Anyway, other databases might have different
1493 * indexes on a given table. So don't bother overriding this unless you're
1494 * MySQL.
1495 */
1496 function useIndexClause( $index ) {
1497 return '';
1498 }
1499
1500 /**
1501 * REPLACE query wrapper
1502 * PostgreSQL simulates this with a DELETE followed by INSERT
1503 * $row is the row to insert, an associative array
1504 * $uniqueIndexes is an array of indexes. Each element may be either a
1505 * field name or an array of field names
1506 *
1507 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1508 * However if you do this, you run the risk of encountering errors which wouldn't have
1509 * occurred in MySQL
1510 *
1511 * @todo migrate comment to phodocumentor format
1512 */
1513 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1514 $table = $this->tableName( $table );
1515
1516 # Single row case
1517 if ( !is_array( reset( $rows ) ) ) {
1518 $rows = array( $rows );
1519 }
1520
1521 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1522 $first = true;
1523 foreach ( $rows as $row ) {
1524 if ( $first ) {
1525 $first = false;
1526 } else {
1527 $sql .= ',';
1528 }
1529 $sql .= '(' . $this->makeList( $row ) . ')';
1530 }
1531 return $this->query( $sql, $fname );
1532 }
1533
1534 /**
1535 * DELETE where the condition is a join
1536 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1537 *
1538 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1539 * join condition matches, set $conds='*'
1540 *
1541 * DO NOT put the join condition in $conds
1542 *
1543 * @param $delTable String: The table to delete from.
1544 * @param $joinTable String: The other table.
1545 * @param $delVar String: The variable to join on, in the first table.
1546 * @param $joinVar String: The variable to join on, in the second table.
1547 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1548 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1549 */
1550 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1551 if ( !$conds ) {
1552 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1553 }
1554
1555 $delTable = $this->tableName( $delTable );
1556 $joinTable = $this->tableName( $joinTable );
1557 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1558 if ( $conds != '*' ) {
1559 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1560 }
1561
1562 return $this->query( $sql, $fname );
1563 }
1564
1565 /**
1566 * Returns the size of a text field, or -1 for "unlimited"
1567 */
1568 function textFieldSize( $table, $field ) {
1569 $table = $this->tableName( $table );
1570 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1571 $res = $this->query( $sql, 'Database::textFieldSize' );
1572 $row = $this->fetchObject( $res );
1573 $this->freeResult( $res );
1574
1575 $m = array();
1576 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1577 $size = $m[1];
1578 } else {
1579 $size = -1;
1580 }
1581 return $size;
1582 }
1583
1584 /**
1585 * A string to insert into queries to show that they're low-priority, like
1586 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1587 * string and nothing bad should happen.
1588 *
1589 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1590 */
1591 function lowPriorityOption() {
1592 return '';
1593 }
1594
1595 /**
1596 * DELETE query wrapper
1597 *
1598 * Use $conds == "*" to delete all rows
1599 */
1600 function delete( $table, $conds, $fname = 'Database::delete' ) {
1601 if ( !$conds ) {
1602 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1603 }
1604 $table = $this->tableName( $table );
1605 $sql = "DELETE FROM $table";
1606 if ( $conds != '*' ) {
1607 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1608 }
1609 return $this->query( $sql, $fname );
1610 }
1611
1612 /**
1613 * INSERT SELECT wrapper
1614 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1615 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1616 * $conds may be "*" to copy the whole table
1617 * srcTable may be an array of tables.
1618 */
1619 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1620 $insertOptions = array(), $selectOptions = array() )
1621 {
1622 $destTable = $this->tableName( $destTable );
1623 if ( is_array( $insertOptions ) ) {
1624 $insertOptions = implode( ' ', $insertOptions );
1625 }
1626 if( !is_array( $selectOptions ) ) {
1627 $selectOptions = array( $selectOptions );
1628 }
1629 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1630 if( is_array( $srcTable ) ) {
1631 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1632 } else {
1633 $srcTable = $this->tableName( $srcTable );
1634 }
1635 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1636 " SELECT $startOpts " . implode( ',', $varMap ) .
1637 " FROM $srcTable $useIndex ";
1638 if ( $conds != '*' ) {
1639 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1640 }
1641 $sql .= " $tailOpts";
1642 return $this->query( $sql, $fname );
1643 }
1644
1645 /**
1646 * Construct a LIMIT query with optional offset. This is used for query
1647 * pages. The SQL should be adjusted so that only the first $limit rows
1648 * are returned. If $offset is provided as well, then the first $offset
1649 * rows should be discarded, and the next $limit rows should be returned.
1650 * If the result of the query is not ordered, then the rows to be returned
1651 * are theoretically arbitrary.
1652 *
1653 * $sql is expected to be a SELECT, if that makes a difference. For
1654 * UPDATE, limitResultForUpdate should be used.
1655 *
1656 * The version provided by default works in MySQL and SQLite. It will very
1657 * likely need to be overridden for most other DBMSes.
1658 *
1659 * @param $sql String: SQL query we will append the limit too
1660 * @param $limit Integer: the SQL limit
1661 * @param $offset Integer the SQL offset (default false)
1662 */
1663 function limitResult( $sql, $limit, $offset=false ) {
1664 if( !is_numeric( $limit ) ) {
1665 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1666 }
1667 return "$sql LIMIT "
1668 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1669 . "{$limit} ";
1670 }
1671 function limitResultForUpdate( $sql, $num ) {
1672 return $this->limitResult( $sql, $num, 0 );
1673 }
1674
1675 /**
1676 * Construct a UNION query
1677 * This is used for providing overload point for other DB abstractions
1678 * not compatible with the MySQL syntax.
1679 * @param $sqls Array: SQL statements to combine
1680 * @param $all Boolean: use UNION ALL
1681 * @return String: SQL fragment
1682 */
1683 function unionQueries($sqls, $all) {
1684 $glue = $all ? ') UNION ALL (' : ') UNION (';
1685 return '('.implode( $glue, $sqls ) . ')';
1686 }
1687
1688 /**
1689 * Returns an SQL expression for a simple conditional. This doesn't need
1690 * to be overridden unless CASE isn't supported in your DBMS.
1691 *
1692 * @param $cond String: SQL expression which will result in a boolean value
1693 * @param $trueVal String: SQL expression to return if true
1694 * @param $falseVal String: SQL expression to return if false
1695 * @return String: SQL fragment
1696 */
1697 function conditional( $cond, $trueVal, $falseVal ) {
1698 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1699 }
1700
1701 /**
1702 * Returns a comand for str_replace function in SQL query.
1703 * Uses REPLACE() in MySQL
1704 *
1705 * @param $orig String: column to modify
1706 * @param $old String: column to seek
1707 * @param $new String: column to replace with
1708 */
1709 function strreplace( $orig, $old, $new ) {
1710 return "REPLACE({$orig}, {$old}, {$new})";
1711 }
1712
1713 /**
1714 * Determines if the last failure was due to a deadlock
1715 * STUB
1716 */
1717 function wasDeadlock() {
1718 return false;
1719 }
1720
1721 /**
1722 * Determines if the last query error was something that should be dealt
1723 * with by pinging the connection and reissuing the query.
1724 * STUB
1725 */
1726 function wasErrorReissuable() {
1727 return false;
1728 }
1729
1730 /**
1731 * Determines if the last failure was due to the database being read-only.
1732 * STUB
1733 */
1734 function wasReadOnlyError() {
1735 return false;
1736 }
1737
1738 /**
1739 * Perform a deadlock-prone transaction.
1740 *
1741 * This function invokes a callback function to perform a set of write
1742 * queries. If a deadlock occurs during the processing, the transaction
1743 * will be rolled back and the callback function will be called again.
1744 *
1745 * Usage:
1746 * $dbw->deadlockLoop( callback, ... );
1747 *
1748 * Extra arguments are passed through to the specified callback function.
1749 *
1750 * Returns whatever the callback function returned on its successful,
1751 * iteration, or false on error, for example if the retry limit was
1752 * reached.
1753 */
1754 function deadlockLoop() {
1755 $myFname = 'Database::deadlockLoop';
1756
1757 $this->begin();
1758 $args = func_get_args();
1759 $function = array_shift( $args );
1760 $oldIgnore = $this->ignoreErrors( true );
1761 $tries = DEADLOCK_TRIES;
1762 if ( is_array( $function ) ) {
1763 $fname = $function[0];
1764 } else {
1765 $fname = $function;
1766 }
1767 do {
1768 $retVal = call_user_func_array( $function, $args );
1769 $error = $this->lastError();
1770 $errno = $this->lastErrno();
1771 $sql = $this->lastQuery();
1772
1773 if ( $errno ) {
1774 if ( $this->wasDeadlock() ) {
1775 # Retry
1776 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1777 } else {
1778 $this->reportQueryError( $error, $errno, $sql, $fname );
1779 }
1780 }
1781 } while( $this->wasDeadlock() && --$tries > 0 );
1782 $this->ignoreErrors( $oldIgnore );
1783 if ( $tries <= 0 ) {
1784 $this->query( 'ROLLBACK', $myFname );
1785 $this->reportQueryError( $error, $errno, $sql, $fname );
1786 return false;
1787 } else {
1788 $this->query( 'COMMIT', $myFname );
1789 return $retVal;
1790 }
1791 }
1792
1793 /**
1794 * Do a SELECT MASTER_POS_WAIT()
1795 *
1796 * @param $pos MySQLMasterPos object
1797 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1798 */
1799 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1800 $fname = 'Database::masterPosWait';
1801 wfProfileIn( $fname );
1802
1803 # Commit any open transactions
1804 if ( $this->mTrxLevel ) {
1805 $this->immediateCommit();
1806 }
1807
1808 if ( !is_null( $this->mFakeSlaveLag ) ) {
1809 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1810 if ( $wait > $timeout * 1e6 ) {
1811 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1812 wfProfileOut( $fname );
1813 return -1;
1814 } elseif ( $wait > 0 ) {
1815 wfDebug( "Fake slave waiting $wait us\n" );
1816 usleep( $wait );
1817 wfProfileOut( $fname );
1818 return 1;
1819 } else {
1820 wfDebug( "Fake slave up to date ($wait us)\n" );
1821 wfProfileOut( $fname );
1822 return 0;
1823 }
1824 }
1825
1826 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1827 $encFile = $this->addQuotes( $pos->file );
1828 $encPos = intval( $pos->pos );
1829 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1830 $res = $this->doQuery( $sql );
1831 if ( $res && $row = $this->fetchRow( $res ) ) {
1832 $this->freeResult( $res );
1833 wfProfileOut( $fname );
1834 return $row[0];
1835 } else {
1836 wfProfileOut( $fname );
1837 return false;
1838 }
1839 }
1840
1841 /**
1842 * Get the position of the master from SHOW SLAVE STATUS
1843 */
1844 function getSlavePos() {
1845 if ( !is_null( $this->mFakeSlaveLag ) ) {
1846 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1847 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1848 return $pos;
1849 }
1850 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1851 $row = $this->fetchObject( $res );
1852 if ( $row ) {
1853 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1854 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1855 } else {
1856 return false;
1857 }
1858 }
1859
1860 /**
1861 * Get the position of the master from SHOW MASTER STATUS
1862 */
1863 function getMasterPos() {
1864 if ( $this->mFakeMaster ) {
1865 return new MySQLMasterPos( 'fake', microtime( true ) );
1866 }
1867 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1868 $row = $this->fetchObject( $res );
1869 if ( $row ) {
1870 return new MySQLMasterPos( $row->File, $row->Position );
1871 } else {
1872 return false;
1873 }
1874 }
1875
1876 /**
1877 * Begin a transaction, committing any previously open transaction
1878 */
1879 function begin( $fname = 'Database::begin' ) {
1880 $this->query( 'BEGIN', $fname );
1881 $this->mTrxLevel = 1;
1882 }
1883
1884 /**
1885 * End a transaction
1886 */
1887 function commit( $fname = 'Database::commit' ) {
1888 $this->query( 'COMMIT', $fname );
1889 $this->mTrxLevel = 0;
1890 }
1891
1892 /**
1893 * Rollback a transaction.
1894 * No-op on non-transactional databases.
1895 */
1896 function rollback( $fname = 'Database::rollback' ) {
1897 $this->query( 'ROLLBACK', $fname, true );
1898 $this->mTrxLevel = 0;
1899 }
1900
1901 /**
1902 * Begin a transaction, committing any previously open transaction
1903 * @deprecated use begin()
1904 */
1905 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1906 $this->begin();
1907 }
1908
1909 /**
1910 * Commit transaction, if one is open
1911 * @deprecated use commit()
1912 */
1913 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1914 $this->commit();
1915 }
1916
1917 /**
1918 * Return MW-style timestamp used for MySQL schema
1919 */
1920 function timestamp( $ts=0 ) {
1921 return wfTimestamp(TS_MW,$ts);
1922 }
1923
1924 /**
1925 * Local database timestamp format or null
1926 */
1927 function timestampOrNull( $ts = null ) {
1928 if( is_null( $ts ) ) {
1929 return null;
1930 } else {
1931 return $this->timestamp( $ts );
1932 }
1933 }
1934
1935 /**
1936 * @todo document
1937 */
1938 function resultObject( $result ) {
1939 if( empty( $result ) ) {
1940 return false;
1941 } elseif ( $result instanceof ResultWrapper ) {
1942 return $result;
1943 } elseif ( $result === true ) {
1944 // Successful write query
1945 return $result;
1946 } else {
1947 return new ResultWrapper( $this, $result );
1948 }
1949 }
1950
1951 /**
1952 * Return aggregated value alias
1953 */
1954 function aggregateValue ($valuedata,$valuename='value') {
1955 return $valuename;
1956 }
1957
1958 /**
1959 * Returns a wikitext link to the DB's website, e.g.,
1960 * return "[http://www.mysql.com/ MySQL]";
1961 * Should at least contain plain text, if for some reason
1962 * your database has no website.
1963 *
1964 * @return String: wikitext of a link to the server software's web site
1965 */
1966 abstract function getSoftwareLink();
1967
1968 /**
1969 * Returns the database type for user-visible purposes
1970 * e.g. DB error messages
1971 * Other uses should just use $wgDBtype
1972 *
1973 * @return String: Database type for use in messages
1974 */
1975 abstract function getDBtypeForMsg();
1976
1977 /**
1978 * A string describing the current software version, like from
1979 * mysql_get_server_info(). Will be listed on Special:Version, etc.
1980 *
1981 * @return String: Version information from the database
1982 */
1983 abstract function getServerVersion();
1984
1985 /**
1986 * Ping the server and try to reconnect if it there is no connection
1987 *
1988 * @return bool Success or failure
1989 */
1990 function ping() {
1991 # Stub. Not essential to override.
1992 return true;
1993 }
1994
1995 /**
1996 * Get slave lag.
1997 * At the moment, this will only work if the DB user has the PROCESS privilege
1998 */
1999 function getLag() {
2000 if ( !is_null( $this->mFakeSlaveLag ) ) {
2001 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2002 return $this->mFakeSlaveLag;
2003 }
2004 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
2005 # Find slave SQL thread
2006 while ( $row = $this->fetchObject( $res ) ) {
2007 /* This should work for most situations - when default db
2008 * for thread is not specified, it had no events executed,
2009 * and therefore it doesn't know yet how lagged it is.
2010 *
2011 * Relay log I/O thread does not select databases.
2012 */
2013 if ( $row->User == 'system user' &&
2014 $row->State != 'Waiting for master to send event' &&
2015 $row->State != 'Connecting to master' &&
2016 $row->State != 'Queueing master event to the relay log' &&
2017 $row->State != 'Waiting for master update' &&
2018 $row->State != 'Requesting binlog dump' &&
2019 $row->State != 'Waiting to reconnect after a failed master event read' &&
2020 $row->State != 'Reconnecting after a failed master event read' &&
2021 $row->State != 'Registering slave on master'
2022 ) {
2023 # This is it, return the time (except -ve)
2024 if ( $row->Time > 0x7fffffff ) {
2025 return false;
2026 } else {
2027 return $row->Time;
2028 }
2029 }
2030 }
2031 return false;
2032 }
2033
2034 /**
2035 * Get status information from SHOW STATUS in an associative array
2036 */
2037 function getStatus($which="%") {
2038 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2039 $status = array();
2040 while ( $row = $this->fetchObject( $res ) ) {
2041 $status[$row->Variable_name] = $row->Value;
2042 }
2043 return $status;
2044 }
2045
2046 /**
2047 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2048 */
2049 function maxListLen() {
2050 return 0;
2051 }
2052
2053 function encodeBlob($b) {
2054 return $b;
2055 }
2056
2057 function decodeBlob($b) {
2058 return $b;
2059 }
2060
2061 /**
2062 * Override database's default connection timeout. May be useful for very
2063 * long batch queries such as full-wiki dumps, where a single query reads
2064 * out over hours or days. May or may not be necessary for non-MySQL
2065 * databases. For most purposes, leaving it as a no-op should be fine.
2066 *
2067 * @param $timeout Integer in seconds
2068 */
2069 public function setTimeout( $timeout ) {}
2070
2071 /**
2072 * Read and execute SQL commands from a file.
2073 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2074 * @param $filename String: File name to open
2075 * @param $lineCallback Callback: Optional function called before reading each line
2076 * @param $resultCallback Callback: Optional function called for each MySQL result
2077 */
2078 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2079 $fp = fopen( $filename, 'r' );
2080 if ( false === $fp ) {
2081 throw new MWException( "Could not open \"{$filename}\".\n" );
2082 }
2083 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2084 fclose( $fp );
2085 return $error;
2086 }
2087
2088 /**
2089 * Get the full path of a patch file. Originally based on archive()
2090 * from updaters.inc. Keep in mind this always returns a patch, as
2091 * it fails back to MySQL if no DB-specific patch can be found
2092 *
2093 * @param $patch String The name of the patch, like patch-something.sql
2094 * @return String Full path to patch file
2095 */
2096 public static function patchPath( $patch ) {
2097 global $wgDBtype, $IP;
2098 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
2099 return "$IP/maintenance/$wgDBtype/archives/$name";
2100 } else {
2101 return "$IP/maintenance/archives/$name";
2102 }
2103 }
2104
2105 /**
2106 * Read and execute commands from an open file handle
2107 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2108 * @param $fp String: File handle
2109 * @param $lineCallback Callback: Optional function called before reading each line
2110 * @param $resultCallback Callback: Optional function called for each MySQL result
2111 */
2112 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2113 $cmd = "";
2114 $done = false;
2115 $dollarquote = false;
2116
2117 while ( ! feof( $fp ) ) {
2118 if ( $lineCallback ) {
2119 call_user_func( $lineCallback );
2120 }
2121 $line = trim( fgets( $fp, 1024 ) );
2122 $sl = strlen( $line ) - 1;
2123
2124 if ( $sl < 0 ) { continue; }
2125 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2126
2127 ## Allow dollar quoting for function declarations
2128 if (substr($line,0,4) == '$mw$') {
2129 if ($dollarquote) {
2130 $dollarquote = false;
2131 $done = true;
2132 }
2133 else {
2134 $dollarquote = true;
2135 }
2136 }
2137 else if (!$dollarquote) {
2138 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2139 $done = true;
2140 $line = substr( $line, 0, $sl );
2141 }
2142 }
2143
2144 if ( '' != $cmd ) { $cmd .= ' '; }
2145 $cmd .= "$line\n";
2146
2147 if ( $done ) {
2148 $cmd = str_replace(';;', ";", $cmd);
2149 $cmd = $this->replaceVars( $cmd );
2150 $res = $this->query( $cmd, __METHOD__ );
2151 if ( $resultCallback ) {
2152 call_user_func( $resultCallback, $res, $this );
2153 }
2154
2155 if ( false === $res ) {
2156 $err = $this->lastError();
2157 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2158 }
2159
2160 $cmd = '';
2161 $done = false;
2162 }
2163 }
2164 return true;
2165 }
2166
2167
2168 /**
2169 * Replace variables in sourced SQL
2170 */
2171 protected function replaceVars( $ins ) {
2172 $varnames = array(
2173 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2174 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2175 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2176 );
2177
2178 // Ordinary variables
2179 foreach ( $varnames as $var ) {
2180 if( isset( $GLOBALS[$var] ) ) {
2181 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2182 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2183 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2184 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2185 }
2186 }
2187
2188 // Table prefixes
2189 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2190 array( $this, 'tableNameCallback' ), $ins );
2191
2192 // Index names
2193 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2194 array( $this, 'indexNameCallback' ), $ins );
2195 return $ins;
2196 }
2197
2198 /**
2199 * Table name callback
2200 * @private
2201 */
2202 protected function tableNameCallback( $matches ) {
2203 return $this->tableName( $matches[1] );
2204 }
2205
2206 /**
2207 * Index name callback
2208 */
2209 protected function indexNameCallback( $matches ) {
2210 return $this->indexName( $matches[1] );
2211 }
2212
2213 /*
2214 * Build a concatenation list to feed into a SQL query
2215 */
2216 function buildConcat( $stringList ) {
2217 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2218 }
2219
2220 /**
2221 * Acquire a named lock
2222 *
2223 * Abstracted from Filestore::lock() so child classes can implement for
2224 * their own needs.
2225 *
2226 * @param $lockName String: Name of lock to aquire
2227 * @param $method String: Name of method calling us
2228 * @return bool
2229 */
2230 public function lock( $lockName, $method, $timeout = 5 ) {
2231 return true;
2232 }
2233
2234 /**
2235 * Release a lock.
2236 *
2237 * @param $lockName String: Name of lock to release
2238 * @param $method String: Name of method calling us
2239 *
2240 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2241 * @return Returns 1 if the lock was released, 0 if the lock was not established
2242 * by this thread (in which case the lock is not released), and NULL if the named
2243 * lock did not exist
2244 */
2245 public function unlock( $lockName, $method ) {
2246 return true;
2247 }
2248
2249 /**
2250 * Lock specific tables
2251 *
2252 * @param $read Array of tables to lock for read access
2253 * @param $write Array of tables to lock for write access
2254 * @param $method String name of caller
2255 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2256 */
2257 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2258 return true;
2259 }
2260
2261 /**
2262 * Unlock specific tables
2263 *
2264 * @param $method String the caller
2265 */
2266 public function unlockTables( $method ) {
2267 return true;
2268 }
2269
2270 /**
2271 * Get search engine class. All subclasses of this
2272 * need to implement this if they wish to use searching.
2273 *
2274 * @return String
2275 */
2276 public function getSearchEngine() {
2277 return "SearchMySQL";
2278 }
2279
2280 /**
2281 * Allow or deny "big selects" for this session only. This is done by setting
2282 * the sql_big_selects session variable.
2283 *
2284 * This is a MySQL-specific feature.
2285 *
2286 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2287 */
2288 public function setBigSelects( $value = true ) {
2289 // no-op
2290 }
2291 }
2292
2293
2294 /******************************************************************************
2295 * Utility classes
2296 *****************************************************************************/
2297
2298 /**
2299 * Utility class.
2300 * @ingroup Database
2301 */
2302 class DBObject {
2303 public $mData;
2304
2305 function DBObject($data) {
2306 $this->mData = $data;
2307 }
2308
2309 function isLOB() {
2310 return false;
2311 }
2312
2313 function data() {
2314 return $this->mData;
2315 }
2316 }
2317
2318 /**
2319 * Utility class
2320 * @ingroup Database
2321 *
2322 * This allows us to distinguish a blob from a normal string and an array of strings
2323 */
2324 class Blob {
2325 private $mData;
2326 function __construct($data) {
2327 $this->mData = $data;
2328 }
2329 function fetch() {
2330 return $this->mData;
2331 }
2332 }
2333
2334 /**
2335 * Utility class.
2336 * @ingroup Database
2337 */
2338 class MySQLField {
2339 private $name, $tablename, $default, $max_length, $nullable,
2340 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2341 function __construct ($info) {
2342 $this->name = $info->name;
2343 $this->tablename = $info->table;
2344 $this->default = $info->def;
2345 $this->max_length = $info->max_length;
2346 $this->nullable = !$info->not_null;
2347 $this->is_pk = $info->primary_key;
2348 $this->is_unique = $info->unique_key;
2349 $this->is_multiple = $info->multiple_key;
2350 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2351 $this->type = $info->type;
2352 }
2353
2354 function name() {
2355 return $this->name;
2356 }
2357
2358 function tableName() {
2359 return $this->tableName;
2360 }
2361
2362 function defaultValue() {
2363 return $this->default;
2364 }
2365
2366 function maxLength() {
2367 return $this->max_length;
2368 }
2369
2370 function nullable() {
2371 return $this->nullable;
2372 }
2373
2374 function isKey() {
2375 return $this->is_key;
2376 }
2377
2378 function isMultipleKey() {
2379 return $this->is_multiple;
2380 }
2381
2382 function type() {
2383 return $this->type;
2384 }
2385 }
2386
2387 /******************************************************************************
2388 * Error classes
2389 *****************************************************************************/
2390
2391 /**
2392 * Database error base class
2393 * @ingroup Database
2394 */
2395 class DBError extends MWException {
2396 public $db;
2397
2398 /**
2399 * Construct a database error
2400 * @param $db Database object which threw the error
2401 * @param $error A simple error message to be used for debugging
2402 */
2403 function __construct( DatabaseBase &$db, $error ) {
2404 $this->db =& $db;
2405 parent::__construct( $error );
2406 }
2407 }
2408
2409 /**
2410 * @ingroup Database
2411 */
2412 class DBConnectionError extends DBError {
2413 public $error;
2414
2415 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2416 $msg = 'DB connection error';
2417 if ( trim( $error ) != '' ) {
2418 $msg .= ": $error";
2419 }
2420 $this->error = $error;
2421 parent::__construct( $db, $msg );
2422 }
2423
2424 function useOutputPage() {
2425 // Not likely to work
2426 return false;
2427 }
2428
2429 function useMessageCache() {
2430 // Not likely to work
2431 return false;
2432 }
2433
2434 function getText() {
2435 return $this->getMessage() . "\n";
2436 }
2437
2438 function getLogMessage() {
2439 # Don't send to the exception log
2440 return false;
2441 }
2442
2443 function getPageTitle() {
2444 global $wgSitename, $wgLang;
2445 $header = "$wgSitename has a problem";
2446 if ( $wgLang instanceof Language ) {
2447 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2448 }
2449
2450 return $header;
2451 }
2452
2453 function getHTML() {
2454 global $wgLang, $wgMessageCache, $wgUseFileCache;
2455
2456 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2457 $again = 'Try waiting a few minutes and reloading.';
2458 $info = '(Can\'t contact the database server: $1)';
2459
2460 if ( $wgLang instanceof Language ) {
2461 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2462 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2463 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2464 }
2465
2466 # No database access
2467 if ( is_object( $wgMessageCache ) ) {
2468 $wgMessageCache->disable();
2469 }
2470
2471 if ( trim( $this->error ) == '' ) {
2472 $this->error = $this->db->getProperty('mServer');
2473 }
2474
2475 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2476 $text = str_replace( '$1', $this->error, $noconnect );
2477
2478 /*
2479 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2480 $text .= '</p><p>Backtrace:</p><p>' .
2481 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2482 "</p>\n";
2483 }*/
2484
2485 $extra = $this->searchForm();
2486
2487 if( $wgUseFileCache ) {
2488 try {
2489 $cache = $this->fileCachedPage();
2490 # Cached version on file system?
2491 if( $cache !== null ) {
2492 # Hack: extend the body for error messages
2493 $cache = str_replace( array('</html>','</body>'), '', $cache );
2494 # Add cache notice...
2495 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2496 # Localize it if possible...
2497 if( $wgLang instanceof Language ) {
2498 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2499 }
2500 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2501 # Output cached page with notices on bottom and re-close body
2502 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2503 }
2504 } catch( MWException $e ) {
2505 // Do nothing, just use the default page
2506 }
2507 }
2508 # Headers needed here - output is just the error message
2509 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2510 }
2511
2512 function searchForm() {
2513 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2514 $usegoogle = "You can try searching via Google in the meantime.";
2515 $outofdate = "Note that their indexes of our content may be out of date.";
2516 $googlesearch = "Search";
2517
2518 if ( $wgLang instanceof Language ) {
2519 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2520 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2521 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2522 }
2523
2524 $search = htmlspecialchars(@$_REQUEST['search']);
2525
2526 $trygoogle = <<<EOT
2527 <div style="margin: 1.5em">$usegoogle<br />
2528 <small>$outofdate</small></div>
2529 <!-- SiteSearch Google -->
2530 <form method="get" action="http://www.google.com/search" id="googlesearch">
2531 <input type="hidden" name="domains" value="$wgServer" />
2532 <input type="hidden" name="num" value="50" />
2533 <input type="hidden" name="ie" value="$wgInputEncoding" />
2534 <input type="hidden" name="oe" value="$wgInputEncoding" />
2535
2536 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2537
2538 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2539 <input type="submit" name="btnG" value="$googlesearch" />
2540 <div>
2541 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2542 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2543 </div>
2544 </form>
2545 <!-- SiteSearch Google -->
2546 EOT;
2547 return $trygoogle;
2548 }
2549
2550 function fileCachedPage() {
2551 global $wgTitle, $title, $wgLang, $wgOut;
2552 if( $wgOut->isDisabled() ) return; // Done already?
2553 $mainpage = 'Main Page';
2554 if ( $wgLang instanceof Language ) {
2555 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2556 }
2557
2558 if( $wgTitle ) {
2559 $t =& $wgTitle;
2560 } elseif( $title ) {
2561 $t = Title::newFromURL( $title );
2562 } else {
2563 $t = Title::newFromText( $mainpage );
2564 }
2565
2566 $cache = new HTMLFileCache( $t );
2567 if( $cache->isFileCached() ) {
2568 return $cache->fetchPageText();
2569 } else {
2570 return '';
2571 }
2572 }
2573
2574 function htmlBodyOnly() {
2575 return true;
2576 }
2577
2578 }
2579
2580 /**
2581 * @ingroup Database
2582 */
2583 class DBQueryError extends DBError {
2584 public $error, $errno, $sql, $fname;
2585
2586 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2587 $message = "A database error has occurred\n" .
2588 "Query: $sql\n" .
2589 "Function: $fname\n" .
2590 "Error: $errno $error\n";
2591
2592 parent::__construct( $db, $message );
2593 $this->error = $error;
2594 $this->errno = $errno;
2595 $this->sql = $sql;
2596 $this->fname = $fname;
2597 }
2598
2599 function getText() {
2600 if ( $this->useMessageCache() ) {
2601 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2602 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ),
2603 htmlspecialchars( $this->db->getDBtypeForMsg() ) ) . "\n";
2604 } else {
2605 return $this->getMessage();
2606 }
2607 }
2608
2609 function getSQL() {
2610 global $wgShowSQLErrors;
2611 if( !$wgShowSQLErrors ) {
2612 return $this->msg( 'sqlhidden', 'SQL hidden' );
2613 } else {
2614 return $this->sql;
2615 }
2616 }
2617
2618 function getLogMessage() {
2619 # Don't send to the exception log
2620 return false;
2621 }
2622
2623 function getPageTitle() {
2624 return $this->msg( 'databaseerror', 'Database error' );
2625 }
2626
2627 function getHTML() {
2628 if ( $this->useMessageCache() ) {
2629 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2630 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ),
2631 htmlspecialchars( $this->db->getDBtypeForMsg() ) );
2632 } else {
2633 return nl2br( htmlspecialchars( $this->getMessage() ) );
2634 }
2635 }
2636 }
2637
2638 /**
2639 * @ingroup Database
2640 */
2641 class DBUnexpectedError extends DBError {}
2642
2643
2644 /**
2645 * Result wrapper for grabbing data queried by someone else
2646 * @ingroup Database
2647 */
2648 class ResultWrapper implements Iterator {
2649 var $db, $result, $pos = 0, $currentRow = null;
2650
2651 /**
2652 * Create a new result object from a result resource and a Database object
2653 */
2654 function ResultWrapper( $database, $result ) {
2655 $this->db = $database;
2656 if ( $result instanceof ResultWrapper ) {
2657 $this->result = $result->result;
2658 } else {
2659 $this->result = $result;
2660 }
2661 }
2662
2663 /**
2664 * Get the number of rows in a result object
2665 */
2666 function numRows() {
2667 return $this->db->numRows( $this );
2668 }
2669
2670 /**
2671 * Fetch the next row from the given result object, in object form.
2672 * Fields can be retrieved with $row->fieldname, with fields acting like
2673 * member variables.
2674 *
2675 * @param $res SQL result object as returned from Database::query(), etc.
2676 * @return MySQL row object
2677 * @throws DBUnexpectedError Thrown if the database returns an error
2678 */
2679 function fetchObject() {
2680 return $this->db->fetchObject( $this );
2681 }
2682
2683 /**
2684 * Fetch the next row from the given result object, in associative array
2685 * form. Fields are retrieved with $row['fieldname'].
2686 *
2687 * @param $res SQL result object as returned from Database::query(), etc.
2688 * @return MySQL row object
2689 * @throws DBUnexpectedError Thrown if the database returns an error
2690 */
2691 function fetchRow() {
2692 return $this->db->fetchRow( $this );
2693 }
2694
2695 /**
2696 * Free a result object
2697 */
2698 function free() {
2699 $this->db->freeResult( $this );
2700 unset( $this->result );
2701 unset( $this->db );
2702 }
2703
2704 /**
2705 * Change the position of the cursor in a result object
2706 * See mysql_data_seek()
2707 */
2708 function seek( $row ) {
2709 $this->db->dataSeek( $this, $row );
2710 }
2711
2712 /*********************
2713 * Iterator functions
2714 * Note that using these in combination with the non-iterator functions
2715 * above may cause rows to be skipped or repeated.
2716 */
2717
2718 function rewind() {
2719 if ($this->numRows()) {
2720 $this->db->dataSeek($this, 0);
2721 }
2722 $this->pos = 0;
2723 $this->currentRow = null;
2724 }
2725
2726 function current() {
2727 if ( is_null( $this->currentRow ) ) {
2728 $this->next();
2729 }
2730 return $this->currentRow;
2731 }
2732
2733 function key() {
2734 return $this->pos;
2735 }
2736
2737 function next() {
2738 $this->pos++;
2739 $this->currentRow = $this->fetchObject();
2740 return $this->currentRow;
2741 }
2742
2743 function valid() {
2744 return $this->current() !== false;
2745 }
2746 }