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