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