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