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